-
Notifications
You must be signed in to change notification settings - Fork 1
/
Import-Font.psm1
370 lines (309 loc) · 12.8 KB
/
Import-Font.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<#
.SYNOPSIS
Import-Font uses the ttx command line tool to import tables from TrueType and OpenType fonts for further processing.
.DESCRIPTION
Import-Font takes a TrueType or OpenType (*.ttf, *.otf) font as an input and returns a custom object containing
font tables in XML format generated by the ttx tool. The object provides a number of methods to modify
those tables.
At this time the following Methods are available:
GetNames(): Gets a list of name entries in the name table.
SetName([int]nameID*, [int]platformID*, [int]encodingID*, [int]langID*, [string]Name*):
Changes a specific name entry to the specified name.
RemoveNames([int]nameID, [int]platformID, [int]encodingID, [int]langID):
Removes one or more name entries from the name table.
Entries will be matched using the specified IDs. Not specifying e.g. the langID will cause all language
versions of entries specified by the supplied IDs to be removed.
GetFsFlags():
Returns a bit flag enum containing the fsSelection flags (Regular, Bold, Italic, ...)
stored in the OS/2 table.
SetsFsFlags([fsSelection]fsFlags*):
Sets the fsSelection flags.
Example: SetFsFlags("Bold, Italic") or SetFsFlags(33)
AddFsFlags([fsSelection]fsFlags):
Adds fsSelection flags and makes sure the resulting value is valid (e.g. not Regular and Bold at the same time)
Example: AddFsFlags("Bold") sets the Bold bit and clears the Regular bit
GetWeight():
Returns the font weight (Light, Regular, Medium, Bold...) as an enum.
SetWeight([usWeightClass]Weight):
Sets the font weight.
GetWidth():
Returns the font width (Normal, Condensed, Expanded...) as an enum.
SetWidth([usWidthClass]Width*):
Sets the font width.
NukeNames([string]type*):
Removes all name table entries of a certain type. Supported Types: all, family, legal
SetNameAuto([int]NameID*, [string]Name*):
Removes all existing table entries associated with the supplied nameID and creates new
English language entries for both the Windows and Macintosh platforms with the specified name.
SetFamily([string]FamilyName, [string]SubFamilyName, [bool]winCompat):
Sets the font name according to supplied Family and Subfamily (style) names.
If FamilyName isn't specified, the value will be taken from the first existing Family name entry.
If SubFamilyName isn't specified, a Style name will be build using the Weight/Width/fsSelection
information in the OS/2 table.
.PARAMETER InFile
Font to import.
Alias: -i
.PARAMETER Tables
Comma-delimited list of tables to import.
Available tables: all, cmap, head, hhea, hmtx, maxp, name, OS/2, post, cvt, fpgm, glyf, loca, prep,
CFF, VORG, BASE, GDEF, GPOS, GSUB, JSTF, DSIG, gasp, hdmx, kern, LTSH, PCLT, VDMX,
vhea, vmtx
Defaults to: name, OS/2, head
Alias: -t
.EXAMPLE
$font = Import-Font X:\font.ttf
.LINK
https://github.com/line0/FontToys
#>
#requires -version 3
function Import-Font {
[CmdletBinding()]
param
(
[Parameter(Position = 0, Mandatory = $true, HelpMessage = 'Path to TrueType/OpenType font to import.')]
[alias("i")]
[string]$InFile,
[Parameter(Mandatory = $false, HelpMessage = 'Comma-delimited list of tables to import.')]
[alias("t")]
[string[]]$Tables = @("name", "OS/2", "head")
)
Check-CmdInPath mkvinfo.exe -Name mkvtoolnix
try {
$font = Get-Files $InFile -match '.[t|o]tf$' -matchDesc "TrueType/OpenType font"
} catch {
if($_.Exception.WasThrownFromThrowStatement -eq $true) {
Write-Host $_.Exception.Message -ForegroundColor Red
break
} else {
throw $_.Exception
}
}
$ttxFile = Join-Path $env:temp ($font.BaseName + ".Import.ttx")
$ttxlog = &ttx $($Tables | ForEach-Object {"-t$_"}) -o $ttxFile $font 2>&1
$ttxFileContent = Get-Content -LiteralPath $ttxFile -Raw
try {
$xml = [xml]$ttxFileContent
} catch {
# if the font has characters w/ broken encoding in name tables, ttx copies writes them to the xml verbatim
# PS chokes on parsing those invalid characters, so we have to nuke them
$xml = [xml]($ttxFileContent -replace "[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD\u10000\u10FFFF]", '')
}
Remove-Item $ttxFile
.(Join-Path (Split-Path -parent $PSCommandPath) "Types.ps1")
$fontInfo = [PSCustomObject]@{
XML = $xml
Path = $font
} |
Add-Member -Name GetNames -PassThru -MemberType ScriptMethod -Value {
param([int]$nameId, [int]$platformId, [int]$encId, [int]$langId)
@{
nameID = $nameId
platformId = $platformId
platEncId = $encId
langId = if ($langId) {
"0x{0:x}" -f $langId
}
}.GetEnumerator() | Where-Object {$_.Value} | ForEach-Object {$names = $this.XML.ttFont.name.namerecord} {
$x = $_; $names = ($names | Where-Object {$_.($x.Key) -eq $x.Value})
}
return $names | Select-Object -Property (
@{Name = "NameID"; Expression = {[int]$_.nameID}},
@{Name = "PlatformID"; Expression = {[int]$_.platformID}},
@{Name = "EncID"; Expression = {[int]$_.platEncID}},
@{Name = "LangID"; Expression = {[int]$_.langId}}, @{Name = "Name"; Expression = {$_."#text".Trim()}}) |
Sort-Object NameID, PlatformID, LangID
} |
Add-Member -Name SetName -PassThru -MemberType ScriptMethod -Value {
param(
[Parameter(Mandatory = $true)]
[int]$nameId,
[Parameter(Mandatory = $true)]
[int]$platformId,
[Parameter(Mandatory = $true)]
[int]$encId,
[Parameter(Mandatory = $true)]
[int]$langId,
[Parameter(Mandatory = $true)]
[string]$name
)
$nameRecord = $this.XML.ttFont.name.namerecord | Where-Object {
$_.nameID -eq $nameId -and $_.platformId -eq $platformId -and $_.langId -eq ("0x{0:x}" -f $langId) -and $_.platEncId -eq $encId
}
if ($nameRecord) {
$nameRecord."#text" = "`n$name`n"
} else {
$newRecord = $this.XML.CreateElement('namerecord')
$newRecord.SetAttribute('nameID', $nameId)
$newRecord.SetAttribute('platformID', $platformId)
$newRecord.SetAttribute('platEncID', $encId)
$newRecord.SetAttribute('langID', "0x{0:x}" -f $langId)
$newRecord.InnerText = $name
$nameRecord = $this.XML.SelectSingleNode('ttFont/name').AppendChild($newRecord)
}
} |
Add-Member -Name RemoveNames -PassThru -MemberType ScriptMethod -Value {
param([int]$nameId, [int]$platformId, [int]$encId, [int]$langId)
# can't reuse $this.GetNames() because we no longer have access to the ParentNode
@{
nameID = $nameId
platformId = $platformId
platEncId = $encId
langId = if ($langId) {
"0x{0:x}" -f $langId
}
}.GetEnumerator() | Where-Object {$_.Value} | ForEach-Object {$names = $this.XML.ttFont.name.namerecord} {
$x = $_; $names = ($names | Where-Object {$_.($x.Key) -eq $x.Value})
}
$names = $names | ForEach-Object {$_.ParentNode.RemoveChild($_)}
} |
Add-Member -Name GetFsFlags -PassThru -MemberType ScriptMethod -Value {
$fsSelInt = [convert]::ToInt32(($this.XML.ttfont.OS_2.fsSelection.value -replace " ", ""), 2)
return [fsSelection]($fsSelInt -band 0x3FF) # bits 10-15 are reserved
} |
Add-Member -Name SetFsFlags -PassThru -MemberType ScriptMethod -Value {
param([fsSelection]$fsSel)
$fsSelBin = [convert]::ToString([int]$fsSel, 2)
$this.XML.ttfont.OS_2.fsSelection.value = ("0" * (16 - $fsSelBin.Length) + $fsSelBin).Insert(8, " ")
} |
Add-Member -Name AddFsFlags -PassThru -MemberType ScriptMethod -Value {
param([int]$fsSel)
$fsSelOld = [int]$this.GetFsFlags()
if ($fsSel % 128 -ne 64 -and $fsSel % 128 -ne 0 -and [fsSelection]$fsSelOld -match "Regular") {
$fsSel = $fsSelOld -bor $fsSel -bxor 64
} elseif ([fsSelection]$fsSel -match "Regular" -and $fsSelOld % 128 -ne 64 ) {
$fsSel = ($fsSel - $fsSel % 128) -bor ($fsSelOld - $fsSelOld % 128) + 64
} else {
$fsSel = $fsSelOld -bor $fsSel
}
$this.SetFsFlags($fsSel)
} |
Add-Member -Name GetWeight -PassThru -MemberType ScriptMethod -Value {
$weight = [int]$this.XML.ttfont.OS_2.usWeightClass.value
$weightClass = $weight -as [usWeightClass]
if ($weightClass) {
return $weightClass;
}
if ($weight -eq 0) {
return [usWeightClass]::Regular
}
if ($weight -le 9) {
# values according to old apple docs
return [usWeightClass]($weight * 100)
}
Write-Warning "$($this.Path.BaseName) has non-standard usWeightClass value $weight"
return [usWeightClass]::Regular
} |
Add-Member -Name SetWeight -PassThru -MemberType ScriptMethod -Value {
param([usWeightClass]$weight)
$this.XML.ttfont.OS_2.usWeightClass.value = [string][int]$weight
} |
Add-Member -Name GetWidth -PassThru -MemberType ScriptMethod -Value {
$width = [int]$this.XML.ttfont.OS_2.usWidthClass.value
$widthClass = $width -as [usWidthClass]
if ($widthClass) {
return $widthClass;
}
if ($width -eq 0) {
return [usWidthClass]::Normal
}
if ($width -le 9) {
# values according to old apple docs
return [usWidthClass]($width * 100)
}
Write-Warning "$($this.Path.BaseName) has non-standard usWidthClass value $width"
return [usWidthClass]::Normal
} |
Add-Member -Name SetWidth -PassThru -MemberType ScriptMethod -Value {
param([usWidthClass]$width)
$this.XML.ttfont.OS_2.usWidthClass.value = [string][int]$width
} |
Add-Member -Name NukeNames -PassThru -MemberType ScriptMethod -Value {
param([string]$type = "all")
$names = switch($type) {
"family" {
@(1, 2, 3, 4, 6, 16, 17, 18)
}
"legal" {
@(0, 7, 13, 14)
}
"all" {
0..30
}
}
$names | ForEach-Object { $this.RemoveNames($_)}
} |
Add-Member -Name SetNameAuto -PassThru -MemberType ScriptMethod -Value {
param([Parameter(Mandatory = $true)][int]$nameId, [Parameter(Mandatory = $true)][string]$name)
$this.RemoveNames($nameId)
$this.SetName($nameId, 1, 0, 0, $name)
$this.SetName($nameId, 3, 1, 1033, $name)
} |
Add-Member -Name SetVersion -PassThru -MemberType ScriptMethod -Value {
param([Parameter(Mandatory = $false)][int]$version, [Parameter(Mandatory = $false)][int]$revision = 0)
if(!$version) {
$regex = "^(\d+)(?:\.(\d+))?"
$matches = Select-String -InputObject $this.XML.ttFont.head.fontRevision.value -pattern $regex | Select-Object -ExpandProperty Matches
[int]$version = $matches.Groups[1].Value
[int]$revision = $matches.Groups[2].Value
} else {
$this.XML.ttFont.head.fontRevision.value = "$version.$revision"
}
$verString = "Version {0}.{1}" -f $version, $revision.ToString("000")
$this.SetNameAuto(5, $verString)
} |
Add-Member -Name SetFamily -PassThru -MemberType ScriptMethod -Value {
param([string]$familyName, [string]$subFamilyName, [bool]$winCompat = $true)
if (!$familyName) {
$familyName = ($this.GetNames(1) | Where-Object {$_.Name.Trim()})[0].Name
}
if (!$subFamilyName) {
$weight = [string]$this.GetWeight()
$width = [string]$this.GetWidth()
$fsFlags = ([string][fsSelection]([int]$this.GetFsFlags() % 128)) -Split ", " | Where-Object {!$weight -or $_ -ne "Bold"}
if ($fsFlags) {
[array]::reverse($fsFlags)
}
$subFamilyName = (@($width, $weight) + $fsFlags | Where-Object {$_ -and $_ -notin @("Regular", "Normal")}) -join " "
if (!$subFamilyName) {
$subFamilyName = "Regular"
}
}
$this.NukeNames("family")
$styleParts = $subFamilyName -split " "
$subFamilyEx = ($styleParts | Where-Object {$_ -notin @("Regular", "Normal")}) -join " "
$this.SetNameAuto(4, @($familyName, $subFamilyEx) -join " ")
$psName = (@($familyName, $subFamilyName) -join "-") -replace " ", ""
$this.SetNameAuto(6, $psName.Substring(0, [Math]::Min($psName.length, 31)))
if ($winCompat) {
$this.SetName(16, 3, 1, 1033, $familyName)
$this.SetName(17, 3, 1, 1033, $subFamilyName)
$splitOff = @("Bold", "Italic", "Regular")
$familyName = @($familyName) + ($styleParts | Where-Object {$_ -notin $splitOff}) -join " "
$subFamilyName = ($styleParts | Where-Object {$_ -in $splitOff}) -join " "
if (!$subFamilyName) {
$subFamilyName = "Regular"
}
}
$this.SetNameAuto(1, $familyName)
$this.SetNameAuto(2, $subFamilyName)
$manuCandidates = @(
$this.GetNames(8, 1, 0, 0).Name,
$this.GetNames(8, 3, 1, 1033).Name,
, @($this.GetNames(8))[0].Name,
$this.GetNames(9, 1, 0, 0).Name,
$this.GetNames(9, 3, 1, 1033).Name,
, @($this.GetNames(9))[0].Name,
"Unknown"
)
foreach($manuCandidate in $manuCandidates) {
if ($manuCandidate -and $manuCandidate.Trim()) {
$manufacturer = $manuCandidate
break;
}
}
$this.SetVersion()
$this.SetNameAuto(3, ("{0}: {1} (FontToys)" -f $manufacturer, $this.GetNames(4, 1, 0, 0).Name))
}
return $fontInfo
}
Export-ModuleMember Import-Font