Debian Codegraph @

texmf-dist/tex/luatex/luaotfload/luaotfload-harf-define.lua

raw
1 -----------------------------------------------------------------------
2 -- FILE: luaotfload-harf-define.lua
3 -- DESCRIPTION: part of luaotfload / HarfBuzz / font definition
4 -----------------------------------------------------------------------
5 do -- block to avoid to many local variables error
6 assert(luaotfload_module, "This is a part of luaotfload and should not be loaded independently") {
7 name = "luaotfload-harf-define",
8 version = "3.29", --TAGVERSION
9 date = "2024-12-03", --TAGDATE
10 description = "luaotfload submodule / HarfBuzz font loading",
11 license = "GPL v2.0",
12 author = "Khaled Hosny, Marcel Krüger",
13 copyright = "Luaotfload Development Team",
14 }
15 end
16
17 local unpack = string.unpack
18 local stringlower = string.lower
19 local stringupper = string.upper
20 local gsub = string.gsub
21 local find = string.find
22 local format = string.format
23
24 local hb = luaotfload.harfbuzz
25 local scriptlang_to_harfbuzz = require'luaotfload-scripts'.to_harfbuzz
26 local cff2_handler = require'luaotfload-harf-var-cff2'
27 local ttf_handler = require'luaotfload-harf-var-ttf'
28
29 local harf_settings = luaotfload.harf or {}
30 luaotfload.harf = harf_settings
31
32 harf_settings.default_buf_flags = hb.Buffer.FLAGS_DEFAULT or 0
33
34 local cfftag = hb.Tag.new("CFF ")
35 local cff2tag = hb.Tag.new("CFF2")
36 local os2tag = hb.Tag.new("OS/2")
37 local posttag = hb.Tag.new("post")
38 local glyftag = hb.Tag.new("glyf")
39 local gpostag = hb.Tag.new("GPOS")
40
41 local italtag = hb.Tag.new("ital")
42 local wghttag = hb.Tag.new("wght")
43 local slnttag = hb.Tag.new("slnt")
44 local opsztag = hb.Tag.new("opsz")
45
46 local invalid_l = hb.Language.new()
47 local invalid_s = hb.Script.new()
48
49 local tointeger = math.tointeger
50 local floor = math.floor
51 local function round(x)
52 return floor(x + 0.5)
53 end
54
55 local get_designsize do
56 -- local lpeg = lpeg or require'lpeg'
57 -- local size_patt = 'size' * lpeg.C(2)/function(s)
58 -- local first, second = string.byte(s)
59 -- return (first << 8) | second
60 -- end
61 -- local factor = 6578.176 -- =803/125*2^10=7227/7200/10*2^16
62 local factor = 6553.6 -- =2^16/10
63 function get_designsize(face)
64 local buf = face:get_table(gpostag):get_data()
65 if #buf == 0 then return 655360 end
66 local major, feature_off = unpack(">HxxxxH", buf)
67 assert(major == 1, "Unsupported major version of GPOS table")
68 local feature_count = unpack(">H", buf, feature_off + 1)
69 for off = feature_off + 3, feature_off + 6*feature_count, 6 do
70 local tag = buf:sub(off, off + 3)
71 if tag == 'size' then
72 local off = feature_off + 1 + unpack(">H", buf, off + 4)
73 local off = off + unpack(">H", buf, off)
74 local design_size = unpack(">H", buf, off) -- unpack(">HHHHH", buf, off))
75 return round(design_size * factor)
76 end
77 end
78 return 655360
79 end
80 end
81
82 local keyhash do
83 local formatstring = string.rep('%02x', 256/8)
84 local sha256 = sha2.digest256
85 local byte = string.byte
86 keyhash = setmetatable({}, {__index = function(t, k)
87 local h = format(formatstring, byte(sha256(k), 1, -1))
88 t[k] = h
89 return h
90 end})
91 end
92
93 local containers = luaotfload.fontloader.containers
94 local hbcacheversion = 1.4
95 local fontcache = containers.define("fonts", "hb", hbcacheversion, true)
96 local facecache = {}
97
98 local variable_pattern do
99 local l = lpeg or require'lpeg'
100 local white = l.S' \t'^0
101 local number = l.C(l.S'+-'^-1 * (l.R'09'^1 * ('.' * l.R'09'^0)^-1 + '.' * l.R'09'^1))
102 local name_or_tag = l.C(l.R('AZ', 'az')^1)
103 local pair = l.Ct(name_or_tag * white * '=' * white * (number + l.Cc(nil) * 'auto'))
104 variable_pattern = l.Ct(pair * (white * ',' * white * pair)^0) * -1
105 end
106
107 local function loadfont(spec)
108 local path, sub = spec.resolved, spec.sub or 1
109
110 local key = format("%s:%d:%s", path, sub, instance)
111
112 local attributes = lfs.attributes(path)
113 if not attributes then return end
114 local size, date = attributes.size or 0, attributes.modification or 0
115
116 local hbface = facecache[key]
117 if not hbface then
118 hbface = hb.Face.new(path, sub - 1)
119 facecache[key] = hbface
120 end
121
122 local normalized
123 local varkey
124 if hbface.ot_var_has_data and hbface:ot_var_has_data() then
125 local design_coords
126 local instance = spec.features.raw.instance
127 local axis = spec.features.raw.axis
128 local assignments = axis and variable_pattern:match(axis)
129 if axis and not assignments and not instance then
130 instance, axis = axis, nil
131 end
132 if instance then
133 instance = instance:lower()
134 local instances = hbface:ot_var_named_instance_get_infos()
135 for i = 1, #instances do
136 local inst = instances[i]
137 if instance == hbface:get_name(inst.subfamily_name_id):lower() then
138 design_coords = {hbface:ot_var_named_instance_get_design_coords(inst.index)}
139 break
140 end
141 end
142 if not design_coords then
143 texio.write_nl'Warning (luaotfload): Unknown instance name ignored.'
144 end
145 end
146 local axes = hbface:ot_var_get_axis_infos()
147 design_coords = design_coords or lua.newtable(#axes, 0)
148 if assignments then
149 for i = 1, #assignments do
150 local found
151 local name = assignments[i][1]
152 local tag
153 if #name <= 4 then
154 tag = hb.Tag.new(name)
155 end
156 name = string.lower(name)
157 for j = 1, #axes do
158 local axis = axes[j]
159 if tag and tag == axis.tag then
160 found = axis
161 break
162 end
163 if name == hbface:get_name(axis.name_id):lower() then
164 found = axis
165 if not tag then break end
166 end
167 end
168 if found then
169 design_coords[found.axis_index] = assignments[i][2]
170 else
171 texio.write_nl'Warning (luaotfload): Unknown axis name ignored.'
172 end
173 end
174 end
175 for i = 1, #axes do
176 local axis = axes[i]
177 local index = axis.axis_index -- == i in practise
178 if not design_coords[index] then
179 local tag = axis.tag
180 if tag == italtag and spec.style then
181 design_coords[index] = spec.style == 'i' or spec.style == 'bi' and 1 or 0
182 elseif tag == slnttag and spec.style then
183 design_coords[index] = spec.style == 'i' or spec.style == 'bi' and -5 or 0
184 elseif tag == wghttag and spec.style then
185 design_coords[index] = (spec.style == 'b' or spec.style == 'bi') and 600 or 400
186 elseif tag == opsztag and (spec.optsize or spec.size > 0) then
187 design_coords[index] = spec.optsize or spec.size / 65536
188 else
189 design_coords[index] = axis.default_value
190 end
191 end
192 end
193 normalized = {hbface:ot_var_normalize_coords(table.unpack(design_coords))}
194 varkey = ':' .. table.concat(normalized, ':')
195 key = key .. varkey
196 else
197 varkey = ''
198 end
199
200 -- Paths get get rather long and contain many characters which can not appear in filenames.
201 -- Therefore we hash the key to get it into a more regular form
202 key = keyhash[key]
203
204 local cached = containers.read(fontcache, key)
205 local iscached = cached and cached.date == date and cached.size == size
206
207 local tags = hbface and hbface:get_table_tags()
208 -- If the face has no table tags then it isn’t a valid SFNT font that
209 -- HarfBuzz can handle.
210 if not tags then return end
211 local hbfont = iscached and cached.font or hb.Font.new(hbface)
212 if normalized then
213 hbfont:set_var_coords_normalized(table.unpack(normalized))
214 end
215
216 if not iscached then
217 local upem = hbface:get_upem()
218
219 -- The engine seems to use the font type to tell whether there is a CFF
220 -- table or not, so we check for that here.
221 local fonttype = nil
222 local hasos2 = false
223 local haspost = false
224 for i = 1, #tags do
225 local tag = tags[i]
226 if tag == cfftag or tag == cff2tag then
227 fonttype = "opentype"
228 elseif tag == glyftag then
229 fonttype = "truetype"
230 elseif tag == os2tag then
231 hasos2 = true
232 elseif tag == posttag then
233 haspost = true
234 end
235 end
236
237 local fontextents = hbfont:get_h_extents()
238 local ascender = fontextents and fontextents.ascender or upem * .8
239 local descender = fontextents and fontextents.descender or upem * .2
240
241 local gid = hbfont:get_nominal_glyph(0x0020)
242 local real_space = hbfont:get_glyph_h_advance(gid or 0)
243 local tex_space = gid and real_space or upem / 2
244
245 local slant = 0
246 if haspost then
247 local post = hbface:get_table(posttag)
248 local length = post:get_length()
249 local data = post:get_data()
250 if length >= 32 and unpack(">i4", data) <= 0x00030000 then
251 local italicangle = unpack(">i4", data, 5) / 2^16
252 if italicangle ~= 0 then
253 slant = -math.tan(italicangle * math.pi / 180) * 65536.0
254 end
255 end
256 end
257
258 -- Load glyph metrics for all glyphs in the font. We used to do this on
259 -- demand to make loading fonts faster, but hit many limitations inside
260 -- the engine (mainly with shared backend fonts, where the engine would
261 -- assume all fonts it decides to share load the same set of glyphs).
262 --
263 -- Getting glyph advances is fast enough, but glyph extents are slower
264 -- especially in CFF fonts. We might want to have an option to ignore exact
265 -- glyph extents and use font ascender and descender if this proved to be
266 -- too slow.
267 local glyphcount = hbface:get_glyph_count()
268 local glyphs = {}
269 local autoitalic = slant ~= 0 and 20 or nil -- the magic 20 is taken from ConTeXt where it came from Dohyun Kim. We keep it to be metric compatible as far as possible
270 for gid = 0, glyphcount - 1 do
271 local width = hbfont:get_glyph_h_advance(gid)
272 local height, depth, italic = nil, nil, nil
273 local extents = hbfont:get_glyph_extents(gid)
274 if extents then
275 height = extents.y_bearing
276 depth = extents.y_bearing + extents.height
277 local right_bearing = extents.x_bearing + extents.width - width
278 if autoitalic and right_bearing > -autoitalic then
279 italic = right_bearing + autoitalic
280 end
281 end
282 glyphs[gid] = {
283 width = width,
284 height = height or ascender,
285 depth = -(depth or descender),
286 italic = italic or 0,
287 }
288 end
289
290 local unicodes = hbface:collect_unicodes()
291 local characters = {}
292 local nominals = {}
293 for _, uni in next, unicodes do
294 local glyph = hbfont:get_nominal_glyph(uni)
295 if glyph then
296 characters[uni] = glyph
297 nominals[glyph] = tointeger(uni)
298 end
299 end
300
301 local xheight, capheight = 0, 0
302 if hasos2 then
303 local os2 = hbface:get_table(os2tag)
304 local length = os2:get_length()
305 local data = os2:get_data()
306 if length >= 96 and unpack(">H", data) > 1 then
307 -- We don’t need much of the table, so we read from hard-coded offsets.
308 xheight = unpack(">H", data, 87)
309 capheight = unpack(">H", data, 89)
310 end
311 end
312
313 if xheight == 0 then
314 local gid = characters[120] -- x
315 if gid then
316 xheight = glyphs[gid].height
317 else
318 xheight = ascender / 2
319 end
320 end
321
322 if capheight == 0 then
323 local gid = characters[88] -- X
324 if gid then
325 capheight = glyphs[gid].height
326 else
327 capheight = ascender
328 end
329 end
330
331 cached = {
332 date = date,
333 size = size,
334 designsize = get_designsize(hbface),
335 gid_offset = 0x120000,
336 upem = upem,
337 fonttype = fonttype,
338 real_space = real_space,
339 tex_space = tex_space,
340 xheight = xheight,
341 capheight = capheight,
342 slant = slant,
343 glyphs = glyphs,
344 nominals = nominals,
345 unicodes = characters,
346 psname = hbface:get_name(hb.ot.NAME_ID_POSTSCRIPT_NAME),
347 fullname = hbface:get_name(hb.ot.NAME_ID_FULL_NAME) .. varkey,
348 haspng = hbface:ot_color_has_png(),
349 loaded = {}, -- Cached loaded glyph data.
350 normalized = normalized,
351 }
352
353 containers.write(fontcache, key, cached)
354 end
355 cached.face = hbface
356 cached.font = hbfont
357 do
358 local nominals = cached.nominals
359 local gid_offset = cached.gid_offset
360 cached.name_to_char = setmetatable({}, {__index = function(t, name)
361 local gid = hbfont:get_glyph_from_name(name)
362 local char = gid and (nominals[gid] or gid_offset + gid)
363 t[name] = char -- ? Do we want this
364 return char
365 end})
366 end
367
368 return cached
369 end
370
371 -- Drop illegal characters from PS Name, per the spec
372 -- https://docs.microsoft.com/en-us/typography/opentype/spec/name#nid6
373 local function sanitize(psname)
374 return psname:gsub('[][\0-\32\127-\255(){}<>/%%]', '-')
375 end
376
377 local function scalefont(data, spec)
378 if not data then return data, spec end
379 local size = spec.size
380 local features = fonts.constructors.checkedfeatures("otf", spec.features.normal)
381 features.mode = 'plug'
382 features.features = 'harf'
383 local hbface = data.face
384 local hbfont = data.font
385 local upem = data.upem
386 local tex_space = data.tex_space
387 local real_space = data.real_space
388 local gid_offset = data.gid_offset
389
390 if size < 0 then
391 size = round(size * data.designsize / -1000)
392 end
393
394 -- We shape in font units (at UPEM) and then scale output with the desired
395 -- sfont size.
396 local scale = size / upem
397 hbfont:set_scale(upem, upem)
398
399 -- Populate font’s characters table.
400 local glyphs = data.glyphs
401 local characters = {}
402 for gid, glyph in next, glyphs do
403 characters[gid_offset + gid] = {
404 index = gid,
405 width = glyph.width * scale,
406 height = glyph.height * scale,
407 depth = glyph.depth * scale,
408 italic = glyph.italic * scale,
409 }
410 end
411
412 local unicodes = data.unicodes
413 for uni, gid in next, unicodes do
414 characters[uni] = characters[gid_offset + gid]
415 characters[uni].tounicode = uni
416 end
417
418 -- Select font palette, we support `palette=index` option, and load the first
419 -- one otherwise.
420 local paletteidx = tonumber(features.palette or features.colr) or 1
421
422 -- Load CPAL palette from the font.
423 local palette = nil
424 if hbface:ot_color_has_palettes() and hbface:ot_color_has_layers() then
425 local count = hbface:ot_color_palette_get_count()
426 if paletteidx <= count then
427 palette = hbface:ot_color_palette_get_colors(paletteidx)
428 end
429 end
430
431 local texname = spec.specification
432 if find(texname, ' ') then
433 texname = format('"%s"', texname) -- Not %q since we do not want escape sequences inside the string
434 end
435
436 local tfmdata = {
437 name = texname,
438 filename = 'harfloaded:' .. spec.resolved,
439 subfont = spec.sub or 1,
440 designsize = data.designsize,
441 psname = sanitize(data.psname),
442 fullname = data.fullname,
443 index = spec.index,
444 size = size,
445 units_per_em = upem,
446 embedding = "subset",
447 tounicode = 1,
448 nomath = true,
449 format = data.fonttype,
450 squeeze = squeezefactor,
451 characters = characters,
452 parameters = {
453 slant = data.slant,
454 space = tex_space * scale,
455 space_stretch = tex_space * scale / 2,
456 space_shrink = tex_space * scale / 3,
457 x_height = data.xheight * scale,
458 quad = size,
459 extra_space = tex_space * scale / 3,
460 [8] = data.capheight * scale, -- for XeTeX compatibility.
461 },
462 hb = {
463 space = (real_space * scale + .5) // 1,
464 scale = scale,
465 palette = palette,
466 shared = data,
467 hscale = upem,
468 vscale = upem,
469 buf_flags = harf_settings.default_buf_flags,
470 obj_repl = characters[0xFFFC] and 0xD800 or 0xFFFC,
471 },
472 specification = spec,
473 shared = {
474 features = features,
475 },
476 properties = {},
477 resources = {
478 unicodes = data.name_to_char,
479 },
480 streamprovider = data.normalized and (data.fonttype == 'opentype' and 1 or 3) or nil,
481 }
482 tfmdata.shared.processes = fonts.handlers.otf.setfeatures(tfmdata, features)
483 fonts.constructors.applymanipulators("otf", tfmdata, features, false)
484 return tfmdata
485 end
486
487 -- Register a reader for `harf` mode (`mode=harf` font option) so that we only
488 -- load fonts when explicitly requested. Fonts we load will be shaped by the
489 -- harf plugin in luaotfload-harf-plug.
490 fonts.readers.harf = function(spec)
491 if not spec.resolved then return end
492 local rawfeatures = spec.features.raw
493 local hb_features = {}
494 spec.hb_features = hb_features
495
496 if rawfeatures.script then
497 local script = stringlower(rawfeatures.script)
498 if script == "dflt" then -- Probably a noop, HarfBuzz normalizes anyway
499 script = "DFLT"
500 end
501 local language = stringupper(rawfeatures.language or 'dflt')
502 language = language == "DFLT" and "dflt" or language
503 local hb_script, hb_lang = scriptlang_to_harfbuzz(script, language)
504 spec.script, spec.language = hb.Script.new(hb_script), hb.Language.new(hb_lang)
505 elseif rawfeatures.language then
506 local language = stringupper(rawfeatures.language)
507 spec.language = hb.Language.new(language == "DFLT" and "dflt"
508 or language)
509 spec.script = invalid_s
510 else
511 spec.script = invalid_s
512 spec.language = invalid_l
513 end
514 for key, val in next, rawfeatures do
515 if key:len() == 4 then
516 -- 4-letter options are likely font features, but not always, so we do
517 -- some checks below. Other options will be queried
518 -- from spec.features.normal.
519 if val == true or val == false then
520 val = (val and '+' or '-')..key
521 hb_features[#hb_features + 1] = hb.Feature.new(val)
522 elseif tonumber(val) then
523 val = '+'..key..'='..tonumber(val)
524 hb_features[#hb_features + 1] = hb.Feature.new(val)
525 end
526 end
527 end
528 return scalefont(loadfont(spec), spec)
529 end
530
531 local find_file = kpse.find_file
532 luatexbase.add_to_callback('find_opentype_file', function(name)
533 return find_file(name, 'opentype fonts')
534 or name:gsub('^harfloaded:', '')
535 end, 'luaotfload.harf.strip_prefix')
536
537 luatexbase.add_to_callback('find_truetype_file', function(name)
538 return find_file(name, 'truetype fonts')
539 or name:gsub('^harfloaded:', '')
540 end, 'luaotfload.harf.strip_prefix')
541
542 local glyph_stream_data
543 local glyph_stream_mapping, glyph_stream_mapping_inverse
544 local extents_hbfont
545 local cb = luatexbase.remove_from_callback('glyph_stream_provider', 'luaotfload.glyph_stream')
546 luatexbase.add_to_callback('glyph_stream_provider', function(fid, cid, kind, ocid)
547 if cid == 0 then -- Always the first call for a font
548 glyph_stream_data, extents_hbfont = nil
549 collectgarbage()
550 local fontdir = font.getfont(fid)
551 if fontdir and fontdir.hb then
552 if kind == 3 then
553 glyph_stream_mapping = {[ocid] = cid}
554 glyph_stream_mapping_inverse = {[cid] = ocid}
555 extents_hbfont = fontdir.hb.shared.font
556 elseif kind == 2 then
557 glyph_stream_data = ttf_handler(fontdir.hb.shared.face, fontdir.hb.shared.font, glyph_stream_mapping, glyph_stream_mapping_inverse)
558 else
559 glyph_stream_data = cff2_handler(fontdir.hb.shared.face, fontdir.hb.shared.font)
560 end
561 end
562 end
563 if glyph_stream_data then
564 return glyph_stream_data(cid)
565 elseif extents_hbfont then
566 glyph_stream_mapping[ocid] = cid
567 glyph_stream_mapping_inverse[cid] = ocid
568 local h_advance = extents_hbfont:get_glyph_h_advance(ocid)
569 local v_advance = extents_hbfont:get_glyph_v_advance(ocid)
570 assert(h_advance and v_advance)
571 local extents = extents_hbfont:get_glyph_extents(ocid)
572 return h_advance, extents and extents.x_bearing or 0, v_advance, 0 -- The last value should be get_glyph_v_origin(ocid).y - extents.y_bearing
573 else
574 return cb(fid, cid, kind, ocid)
575 end
576 end, 'luaotfload.harf.glyphstream')