Debian Codegraph @

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

raw
1 -----------------------------------------------------------------------
2 -- FILE: luaotfload-harf-plug.lua
3 -- DESCRIPTION: part of luaotfload / HarfBuzz / fontloader plugin
4 -----------------------------------------------------------------------
5 assert(luaotfload_module, "This is a part of luaotfload and should not be loaded independently") {
6 name = "luaotfload-harf-plug",
7 version = "3.29", --TAGVERSION
8 date = "2024-12-03", --TAGDATE
9 description = "luaotfload submodule / HarfBuzz shaping",
10 license = "GPL v2.0",
11 author = "Khaled Hosny, Marcel Krüger",
12 copyright = "Luaotfload Development Team",
13 }
14
15 local hb = luaotfload.harfbuzz
16 local logreport = luaotfload.log.report
17
18 local assert = assert
19 local next = next
20 local tonumber = tonumber
21 local type = type
22 local format = string.format
23 local open = io.open
24 local tableinsert = table.insert
25 local tableremove = table.remove
26 local ostmpdir = os.tmpdir
27 local osremove = os.remove
28 local dir = lfs.dir
29 local rmdir = lfs.rmdir
30
31 local direct = node.direct
32 local tonode = direct.tonode
33 local todirect = direct.todirect
34 local traverse = direct.traverse
35 local traverse_list = direct.traverse_list
36 local insertbefore = direct.insert_before
37 local insertafter = direct.insert_after
38 local protectglyph = direct.protect_glyph
39 local newnode = direct.new
40 local freenode = direct.free
41 local copynode = direct.copy
42 local removenode = direct.remove
43 local copynodelist = direct.copy_list
44 local ischar = direct.is_char
45 local uses_font = direct.uses_font
46 local length = direct.length
47
48 local getattrs = direct.getattributelist
49 local setattrs = direct.setattributelist
50 local getchar = direct.getchar
51 local setchar = direct.setchar
52 local getdirection = direct.getdirection
53 local getdisc = direct.getdisc
54 local setdisc = direct.setdisc
55 local getfont = direct.getfont
56 local getdata = direct.getdata
57 local setdata = direct.setdata
58 local getfont = direct.getfont
59 local setfont = direct.setfont
60 local getwhatsitfield = direct.getwhatsitfield or direct.getfield
61 local setwhatsitfield = direct.setwhatsitfield or direct.setfield
62 local getfield = direct.getfield
63 local setfield = direct.setfield
64 local getid = direct.getid
65 local getkern = direct.getkern
66 local setkern = direct.setkern
67 local getnext = direct.getnext
68 local setnext = direct.setnext
69 local getoffsets = direct.getoffsets
70 local setoffsets = direct.setoffsets
71 local getproperty = direct.getproperty
72 local setproperty = direct.setproperty
73 local getprev = direct.getprev
74 local setprev = direct.setprev
75 local getsubtype = direct.getsubtype
76 local setsubtype = direct.setsubtype
77 local getwidth = direct.getwidth
78 local setwidth = direct.setwidth
79 local setlist = direct.setlist
80 local is_char = direct.is_char
81 local tail = direct.tail
82 local getboth = direct.getboth
83 local setlink = direct.setlink
84
85 local properties = direct.get_properties_table()
86
87 local hlist_t = node.id("hlist")
88 local disc_t = node.id("disc")
89 local glue_t = node.id("glue")
90 local glyph_t = node.id("glyph")
91 local dir_t = node.id("dir")
92 local kern_t = node.id("kern")
93 local localpar_t = node.id("local_par")
94 local whatsit_t = node.id("whatsit")
95 local pdfliteral_t = node.subtype("pdf_literal")
96
97 local line_t = 1
98 local explicitdisc_t = 1
99 local firstdisc_t = 4
100 local seconddisc_t = 5
101 local fontkern_t = 0
102 local italiccorr_t = 3
103 local regulardisc_t = 3
104 local spaceskip_t = 13
105
106 local dir_ltr = hb.Direction.new("ltr")
107 local dir_rtl = hb.Direction.new("rtl")
108 local fl_unsafe = hb.Buffer.GLYPH_FLAG_UNSAFE_TO_BREAK
109
110 local startactual_p = "luaotfload_startactualtext"
111 local endactual_p = "luaotfload_endactualtext"
112
113 local empty_table = {}
114
115 local function is_empty_disc(n)
116 local pre, post, rep = getdisc(n)
117 return not pre and not post and not rep
118 end
119
120 -- "Copy" properties as done by LuaTeX: Make old properties metatable
121 local function copytable(old)
122 local new = {}
123 for k, v in next, old do
124 if type(v) == "table" then v = copytable(v) end
125 new[k] = v
126 end
127 setmetatable(new, getmetatable(old))
128 return new
129 end
130
131 -- Set and get properties.
132 local function setprop(n, prop, value)
133 local props = properties[n]
134 if not props then
135 props = {}
136 properties[n] = props
137 end
138 props[prop] = value
139 end
140
141 local function inherit(t, sub, base, properties)
142 local n = newnode(t, sub)
143 setattrs(n, getattrs(base))
144 if properties then
145 setproperty(n, setmetatable({}, {__index = properties}))
146 end
147 return n
148 end
149 -- New kern node of amount `v`, inheriting the properties/attributes of `n`.
150 local function newkern(v, n)
151 local kern = inherit(kern_t, 0, n, getproperty(n))
152 setkern(kern, v)
153 return kern
154 end
155
156 local function insertkern(head, current, kern, rtl)
157 if rtl then
158 head = insertbefore(head, current, kern)
159 else
160 head, current = insertafter(head, current, kern)
161 end
162 return head, current
163 end
164
165 -- Convert list of integers to UTF-16 hex string used in PDF.
166 local function to_utf16_hex(uni)
167 if uni < 0x10000 then
168 return format("%04X", uni)
169 else
170 uni = uni - 0x10000
171 local hi = 0xD800 + (uni // 0x400)
172 local lo = 0xDC00 + (uni % 0x400)
173 return format("%04X%04X", hi, lo)
174 end
175 end
176
177 local process
178
179 local function itemize(head, fontid, direction)
180 local fontdata = font.getfont(fontid)
181 local hbdata = fontdata and fontdata.hb
182 local spec = fontdata and fontdata.specification
183 local options = spec and spec.features.raw
184 local obj_repl = hbdata and hbdata.obj_repl
185
186 local runs, codes = {}, {}
187 local dirstack = {}
188 local currdir = direction or 0
189 local lastskip, lastdir = true
190 local dummyrun = { start = 0, len = 0 }
191 local lastrun = dummyrun
192 local lastdisc
193 local in_disc
194
195 for n, id, subtype in traverse(head) do
196 if in_disc == n then in_disc = nil end
197 local disc
198 local code = obj_repl -- OBJECT REPLACEMENT CHARACTER, substitute invalid surrogate if otherwise colliding with font glyph
199 local skip = lastskip
200 local props = properties[n]
201
202 if props and props.zwnj then
203 code = 0x200C
204 -- skip = false -- Not sure about this, but lastskip should be a bit faster
205 elseif id == glyph_t then
206 local char = is_char(n, fontid)
207 if char then
208 code = char
209 skip = false
210 else
211 skip = true
212 end
213 elseif id == glue_t and subtype == spaceskip_t then
214 code = 0x0020 -- SPACE
215 elseif id == disc_t then
216 if uses_font(n, fontid) or not lastskip and is_empty_disc(n) then
217 local _, _, rep, _, _, rep_tail = getdisc(n, true)
218 setfield(n, 'replace', nil)
219 local prev, next = getboth(n)
220 in_disc = next
221 disc = {
222 disc = n,
223 anchor_cluster = #codes - (lastrun.start or 0) + 1,
224 after_cluster = #codes - (lastrun.start or 0) + 1 + length(rep),
225 }
226 if rep then
227 setlink(rep_tail, next)
228 setnext(n, rep) -- This one is just to keep the loop going
229 n = rep
230 else
231 n = next
232 end
233 setlink(prev, n)
234 code = nil
235 skip = false
236 else
237 skip = true
238 end
239 elseif id == dir_t then
240 local dir, cancel = getdirection(n)
241 local direction, kind = getdirection(n)
242 if cancel then
243 assert(currdir == dir)
244 -- Pop the last direction from the stack.
245 currdir = tableremove(dirstack)
246 else
247 -- Push the current direction to the stack.
248 tableinsert(dirstack, currdir)
249 currdir = dir
250 end
251 elseif id == localpar_t then
252 currdir = getdirection(n)
253 end
254
255 local ncodes = #codes -- Necessary to count discs correctly
256 codes[ncodes + 1] = code
257
258 if (disc or not in_disc) and (lastdir ~= currdir or lastskip ~= skip) then
259 if disc then
260 disc.after_cluster = disc.after_cluster - disc.anchor_cluster
261 disc.anchor_cluster = 0
262 end
263 lastrun.after = n
264 lastrun = {
265 start = ncodes + 1,
266 len = code and 1 or 0,
267 font = fontid,
268 dir = currdir == 1 and dir_rtl or dir_ltr,
269 skip = skip,
270 codes = codes,
271 discs = disc,
272 }
273 runs[#runs + 1] = lastrun
274 lastdir, lastskip, lastdisc = currdir, skip, disc
275 elseif code then
276 lastrun.len = lastrun.len + 1
277 elseif disc then
278 if lastdisc then
279 if lastrun.len == 0 then
280 runs[#runs - 1].after = n
281 end
282 lastdisc.next = disc
283 lastdisc = disc
284 else
285 lastrun.discs, lastdisc = disc, disc
286 end
287 end
288 end
289
290 return dummyrun.after, runs
291 end
292
293
294 -- Check if it is not safe to break before this glyph.
295 local function unsafetobreak(glyph)
296 return glyph
297 and glyph.flags
298 and glyph.flags & fl_unsafe ~= 0
299 end
300
301 local shape
302
303 -- Make s a sub run, used by discretionary nodes.
304 local function makesub(run, codes, nodelist)
305 local subrun = {
306 start = 1,
307 len = #codes,
308 font = run.font,
309 dir = run.dir,
310 fordisc = true,
311 codes = codes,
312 }
313 local glyphs
314 if nodelist == 0 then -- FIXME: This shouldn't happen
315 nodelist = nil
316 end
317 nodelist, nodelist, glyphs = shape(nodelist, nodelist, subrun)
318 assert(glyphs, [[Shaping discretionary list failed. This shouldn't happen.]])
319 return { glyphs = glyphs, run = subrun, head = nodelist }
320 end
321
322 local function printnodes(label, head, after)
323 after = tonode(after)
324 for n in node.traverse(tonode(head)) do
325 if n == after then return end
326 print(label, n, n.font or '', n.char or '')
327 local pre, post, rep = getdisc(todirect(n))
328 if pre then
329 printnodes(label .. '<', pre)
330 end
331 if post then
332 printnodes(label .. '>', post)
333 end
334 if rep then
335 printnodes(label .. '=', rep)
336 end
337 end
338 end
339 -- Main shaping function that calls HarfBuzz, and does some post-processing of
340 -- the output.
341 function shape(head, firstnode, run)
342 local node = firstnode
343 local codes = run.codes
344 local offset = run.start - 1 -- -1 because we want the cluster
345 local len = run.len
346 local fontid = run.font
347 local dir = run.dir
348 local cluster
349 local discs = (not run.fordisc) and run.discs
350
351 local fontdata = font.getfont(fontid)
352 local hbdata = fontdata.hb
353 local spec = fontdata.specification
354 local features = spec.hb_features
355 local options = spec.features.raw
356 local hbshared = hbdata.shared
357 local hbfont = hbshared.font
358 local obj_repl = hbdata.obj_repl
359
360 local lang = spec.language
361 local script = spec.script
362 local shapers = options.shaper and { options.shaper } or {}
363
364 local buf = hb.Buffer.new()
365 if buf.set_flags then
366 buf:set_flags(hbdata.buf_flags)
367 end
368 buf:set_direction(dir)
369 buf:set_script(script)
370 buf:set_language(lang)
371 buf:set_cluster_level(buf.CLUSTER_LEVEL_MONOTONE_CHARACTERS)
372 buf:add_codepoints(codes, offset, len)
373
374 local hscale = hbdata.hscale
375 local vscale = hbdata.vscale
376 hbfont:set_scale(hscale, vscale)
377
378 do
379 features = table.merged(features) -- We don't want to modify the global features
380 local current_features = {}
381 local n = node
382 for i = offset, offset+len-1 do
383 local props = properties[n] or empty_table
384 if props then
385 local local_feat = props.glyph_features or empty_table
386 if local_feat then
387 for tag, value in next, current_features do
388 local loc = local_feat[tag]
389 loc = loc ~= nil and (tonumber(loc) or (loc and 1 or 0)) or nil
390 if value.value ~= loc then -- This includes loc == nil
391 value._end = i
392 features[#features + 1] = value
393 current_features[tag] = nil
394 end
395 end
396 for tag, value in next, local_feat do
397 if not current_features[tag] then
398 local feat = hb.Feature.new(tag)
399 feat.value = tonumber(value) or (value and 1 or 0)
400 feat.start = i
401 current_features[tag] = feat
402 end
403 end
404 end
405 end
406 n = getnext(n)
407 end
408 for _, feat in next, current_features do
409 features[#features + 1] = feat
410 end
411 end
412
413 if hb.shape_full(hbfont, buf, features, shapers) then
414 -- The engine wants the glyphs in logical order, but HarfBuzz outputs them
415 -- in visual order, so we reverse RTL buffers.
416 if dir:is_backward() then buf:reverse() end
417
418 local glyphs = buf:get_glyphs()
419
420 local break_glyph, break_cluster, break_node = 1, offset, node
421 local disc_glyph, disc_cluster, disc_node
422 local disc_cluster
423 local i = 0
424 local glyph
425 -- The following is a repeat {...} while glyph {...} loop.
426 while true do
427 repeat
428 i = i+1
429 glyph = glyphs[i]
430 until not glyph or glyph.cluster ~= cluster
431 do
432 local oldcluster = cluster
433 cluster = glyph and glyph.cluster or offset + len
434 if oldcluster then
435 for _ = oldcluster+1, cluster do
436 node = getnext(node)
437 end
438 end
439 end
440
441 -- Is this a safe breakpoint?
442 if discs and ((not glyph)
443 or codes[cluster] == 0x20 or codes[cluster+1] == 0x20
444 or codes[cluster] == obj_repl or codes[cluster+1] == obj_repl
445 or not unsafetobreak(glyph)) then
446 -- Should we change the discretionary state?
447 local anchor_cluster, after_cluster = offset + discs.anchor_cluster, offset + discs.after_cluster
448 local saved_anchor, saved_after = (discs.next and discs.next.anchor_cluster or math.huge) + offset
449 while disc_cluster and after_cluster <= cluster
450 or not disc_cluster and anchor_cluster <= cluster do
451 if disc_cluster then
452 if false then -- The saved_... are for nested (aka first/second or init/select) discretionary nodes. The code is currently disabled because the linebreaking for these is broken on the engine level.
453 if not saved_after and saved_anchor < cluster then
454 saved_after = discs.next.after_cluster + offset
455 if saved_after > cluster then
456 saved_after, after_cluster = after_cluster, saved_after
457 break
458 end
459 elseif saved_after then
460 saved_after, after_cluster = after_cluster, saved_after
461 end
462 end
463 local rep_glyphs = table.move(glyphs, disc_glyph, i - 1, 1, {})
464 for j = 1, #rep_glyphs do
465 local glyph = rep_glyphs[j]
466 glyph.cluster = glyph.cluster - disc_cluster
467 if glyph.nextcluster then
468 glyph.nextcluster = glyph.nextcluster - disc_cluster
469 end
470 end
471 do
472 local cluster_offset = disc_cluster - cluster + (saved_after and 2 or 1) -- The offset the glyph indices will move
473 for j = i, #glyphs do
474 local glyph = glyphs[j]
475 glyph.cluster = glyph.cluster + cluster_offset
476 end
477 len = len + cluster_offset
478 table.move(glyphs, i, #glyphs + i - disc_glyph, disc_glyph + (saved_after and 2 or 1))
479
480 local discs = discs.next
481 while discs do
482 discs.anchor_cluster = discs.anchor_cluster + cluster_offset
483 discs.after_cluster = discs.after_cluster + cluster_offset
484 discs = discs.next
485 end
486 end
487
488 local pre, post, _, _, lastpost, _ = getdisc(discs.disc, true)
489 local precodes, postcodes, repcodes = {}, {}
490 table.move(codes, disc_cluster + 1, anchor_cluster, 1, precodes)
491 for n in traverse(pre) do
492 precodes[#precodes + 1] = is_char(n, fontid) or obj_repl
493 end
494 for n in traverse(post) do
495 postcodes[#postcodes + 1] = is_char(n, fontid) or obj_repl
496 end
497 table.move(codes, after_cluster + 1, cluster, #postcodes + 1, postcodes)
498
499 if saved_after then
500 repcodes = table.move(codes, disc_cluster + 1, cluster, 1, {})
501 table.move(codes, cluster + 1, #codes + cluster - disc_cluster, disc_cluster + 3)
502 codes[disc_cluster + 1], codes[disc_cluster + 2] = obj_repl, obj_repl
503 else
504 table.move(codes, cluster + 1, #codes + cluster - disc_cluster, disc_cluster + 2)
505 codes[disc_cluster + 1] = obj_repl
506 end
507
508 do
509 local iter = disc_node
510 for _ = disc_cluster, anchor_cluster-1 do iter = getnext(iter) end
511 if iter ~= disc_node then
512 local newpre = copynodelist(disc_node, iter)
513 setlink(tail(newpre), pre)
514 pre = newpre
515 end
516 for _ = anchor_cluster, after_cluster-1 do iter = getnext(iter) end
517 if post then
518 setlink(lastpost, copynodelist(iter, node))
519 else
520 post = copynodelist(iter, node)
521 end
522 end
523 local prev = getprev(disc_node)
524 if disc_cluster ~= cluster then
525 setprev(disc_node, nil)
526 setnext(getprev(node), nil)
527 end
528 setlink(prev, discs.disc, node)
529 if disc_node == firstnode then
530 firstnode = discs.disc
531 if head == disc_node then
532 head = firstnode
533 end
534 end
535 glyphs[disc_glyph] = {
536 replace = {
537 glyphs = rep_glyphs,
538 head = disc_node ~= node and disc_node or nil,
539 run = {
540 start = 1,
541 font = run.font,
542 dir = run.dir,
543 },
544 },
545 pre = makesub(run, precodes, pre),
546 post = makesub(run, postcodes, post),
547 cluster = disc_cluster,
548 nextcluster = disc_cluster + 1,
549 codepoint = obj_repl,
550 }
551 if saved_after then
552 local next_disc = discs.next
553 setlink(discs.disc, next_disc.disc, node)
554 local next_pre, next_post, _, _, next_lastpost, _ = getdisc(next_disc.disc, true)
555 local next_rep = copynodelist(next_pre)
556 -- Let's play the game again. We need three parts:
557 -- The pre and post branches in the outer post branch
558 local next_precodes, next_postcodes, next_repcodes = {}, {}, {}
559 do
560 local saved_offset = length(post) - cluster
561 local saved_anchor, saved_after = saved_anchor + saved_offset, saved_after + saved_offset
562 table.move(postcodes, 1, saved_anchor, 1, next_precodes)
563 for n in traverse(next_pre) do
564 next_precodes[#next_precodes + 1] = is_char(n, fontid) or obj_repl
565 end
566 for n in traverse(next_post) do
567 next_postcodes[#next_postcodes + 1] = is_char(n, fontid) or obj_repl
568 end
569 table.move(postcodes, saved_after + 1, #postcodes, #next_postcodes + 1, next_postcodes)
570
571 local iter = post
572 for _ = 1, saved_anchor do iter = getnext(iter) end
573 if iter ~= post then
574 local newpre = copynodelist(post, iter)
575 setlink(tail(newpre), next_pre)
576 next_pre = newpre
577 end
578 for _ = saved_anchor, saved_after - 1 do iter = getnext(iter) end
579 if next_post then
580 setlink(next_lastpost, copynodelist(iter))
581 else
582 next_post = copynodelist(iter)
583 end
584 end
585 -- The pre branch in the outer replace branch. The post branch is implicitly the same as the previous one
586 do
587 local saved_anchor = saved_anchor - disc_cluster
588 table.move(repcodes, 1, saved_anchor, 1, next_repcodes)
589 for n in traverse(next_rep) do
590 next_repcodes[#next_repcodes + 1] = is_char(n, fontid) or obj_repl
591 end
592
593 local rep = glyphs[disc_glyph].replace.head
594 local iter = rep
595 for _ = 1, saved_anchor do iter = getnext(iter) end
596 if iter ~= rep then
597 local newpre = copynodelist(rep, iter)
598 setlink(tail(newpre), next_rep)
599 next_rep = newpre
600 end
601 end
602 setsubtype(discs.disc, firstdisc_t)
603 setsubtype(next_disc.disc, seconddisc_t)
604 discs = discs.next
605 disc_glyph = disc_glyph + 1
606 disc_cluster = disc_cluster + 1
607 glyphs[disc_glyph] = {
608 replace = makesub(run, next_repcodes, next_rep),
609 pre = makesub(run, next_precodes, next_pre),
610 post = makesub(run, next_postcodes, next_post),
611 cluster = disc_cluster,
612 nextcluster = disc_cluster + 1,
613 codepoint = obj_repl,
614 }
615 end
616 i = disc_glyph + 1
617 assert(node == getnext(discs.disc))
618 cluster = disc_cluster + 1
619
620 disc_cluster = nil
621 discs = discs.next
622 while discs and discs.anchor_cluster + offset < cluster do
623 freenode(discs.disc)
624 discs = discs.next
625 end
626 if not discs then break end
627 anchor_cluster, after_cluster = offset + discs.anchor_cluster, offset + discs.after_cluster
628 saved_anchor, saved_after = (discs.next and discs.next.anchor_cluster or math.huge) + offset
629 elseif anchor_cluster == cluster then
630 disc_glyph, disc_cluster, disc_node = i, cluster, node
631 else
632 disc_glyph, disc_cluster, disc_node = break_glyph, break_cluster, break_node
633 end
634 end
635 break_glyph, break_cluster, break_node = i, cluster, node
636 end
637
638 if not glyph then break end
639
640 local nextcluster
641 for j = i+1, #glyphs do
642 nextcluster = glyphs[j].cluster
643 if cluster ~= nextcluster then
644 glyph.nglyphs = j - i
645 goto NEXTCLUSTERFOUND -- break
646 end
647 end -- else -- only executed if the loop reached the end without
648 -- finding another cluster
649 nextcluster = offset + len
650 glyph.nglyphs = #glyphs + 1 - i
651 ::NEXTCLUSTERFOUND:: -- end
652 glyph.nextcluster = nextcluster
653
654 -- Calculate the Unicode code points of this glyph. If cluster did not
655 -- change then this is a glyph inside a complex cluster and will be
656 -- handled with the start of its cluster.
657 do
658 local hex = ""
659 local str = ""
660 local node = node
661 for j = cluster+1,nextcluster do
662 local char, id = is_char(node, fontid)
663 if char then
664 -- assert(char == codes[j])
665 hex = hex .. to_utf16_hex(char)
666 str = str .. utf8.char(char)
667 end
668 node = getnext(node)
669 end
670 glyph.tounicode = hex
671 glyph.string = str
672 end
673 end
674 return head, firstnode, glyphs, run.len - len
675 else
676 if not fontdata.shaper_warning then
677 local shaper = shapers[1]
678 if shaper then
679 tex.error("luaotfload | harf : Shaper failed", {
680 string.format("You asked me to use shaper %q to shape", shaper),
681 string.format("the font %q", fontdata.name),
682 "but the shaper failed. This probably means that either the shaper is not",
683 "available or the font is not compatible.",
684 "Maybe you should try the default shaper instead?"
685 })
686 else
687 tex.error(string.format("luaotfload | harf : All shapers failed for font %q.", fontdata.name))
688 end
689 fontdata.shaper_warning = true -- Only warn once for every font
690 end
691 end
692 end
693
694 local function color_to_rgba(color)
695 local r = color.red / 255
696 local g = color.green / 255
697 local b = color.blue / 255
698 local a = color.alpha / 255
699 if a ~= 1 then
700 -- XXX: alpha
701 return format('%s %s %s rg', r, g, b)
702 else
703 return format('%s %s %s rg', r, g, b)
704 end
705 end
706
707 -- Cache of color glyph PNG data for bookkeeping, only because I couldn't
708 -- figure how to make the engine load the image from the binary data directly.
709 local tmpdirname
710 local tmpcount = 0
711 local pngcache = {}
712 local pngcachefiles = {}
713 local function cachedpng(data)
714 local hash = md5.sumhexa(data)
715 local i = pngcache[hash]
716 if not i then
717 tmpdirname = tmpdirname or ostmpdir()
718 tmpcount = tmpcount + 1
719 local path = format('%s/%i.png', tmpdirname, tmpcount)
720 pngcachefiles[#pngcachefiles + 1] = path
721 open(path, "wb"):write(data):close()
722 -- local file = open(path, "wb"):write():close()
723 -- file:write(data)
724 -- file:close()
725 i = img.scan{filename = path}
726 pngcache[hash] = i
727 end
728 return i
729 end
730
731 local function get_png_glyph(gid, fontid, characters, haspng)
732 return gid
733 end
734
735 local push_cmd = { "push" }
736 local pop_cmd = { "pop" }
737 local nop_cmd = { "nop" }
738 --[[
739 In the following, "text" actually refers to "font" mode and not to "text"
740 mode. "font" mode is called "text" inside of virtual font commands (don't
741 ask me why, but the LuaTeX source does make it clear that this is intentional)
742 and behaves mostly like "page" (especially it does not enter a "BT" "ET"
743 block) except that it always resets the current position to the origin.
744 This is necessary to ensure that the q/Q pair does not interfere with TeX's
745 position tracking.
746 ]]
747 local save_cmd = { "pdf", "text", "q" }
748 local restore_cmd = { "pdf", "text", "Q" }
749
750 -- Convert glyphs to nodes and collect font characters.
751 local function tonodes(head, node, run, glyphs)
752 local nodeindex = run.start
753 local dir = run.dir
754 local fontid = run.font
755 local fontdata = font.getfont(fontid)
756 local characters = fontdata.characters
757 local hbdata = fontdata.hb
758 local hfactor = (fontdata.extend or 1000) / 1000
759 local palette = hbdata.palette
760 local hbshared = hbdata.shared
761 local hbface = hbshared.face
762 local nominals = hbshared.nominals
763 local hbfont = hbshared.font
764 local fontglyphs = hbshared.glyphs
765 local gid_offset = hbshared.gid_offset
766 local rtl = dir:is_backward()
767 local lastprops
768
769 local scale = hbdata.scale
770 local space = hbdata.space
771
772 local haspng = hbshared.haspng
773 local fonttype = hbshared.fonttype
774
775 local nextcluster
776
777 for i, glyph in ipairs(glyphs) do
778 if glyph.cluster + 1 >= nodeindex then -- Reached a new cluster
779 nextcluster = glyph.nextcluster
780 assert(nextcluster)
781 for j = nodeindex, glyph.cluster do
782 local oldnode = node
783 head, node = removenode(head, node)
784 freenode(oldnode)
785 end
786 lastprops = getproperty(node)
787 nodeindex = glyph.cluster + 1
788 elseif nextcluster + 1 == nodeindex then -- Oops, we went too far
789 nodeindex = nodeindex - 1
790 if node then
791 local new = inherit(glyph_t, 0, getprev(node), lastprops)
792 head, node = insertbefore(head, node, new)
793 else
794 node = tail(head)
795 local new = inherit(glyph_t, 0, node, lastprops)
796 head, node = insertafter(head, node, new)
797 end
798 setfont(node, fontid)
799 end
800 local gid = glyph.codepoint
801 local char = nominals[gid] or gid_offset + gid
802 local orig_char, id = is_char(node, fontid)
803
804 if glyph.replace then
805 -- For discretionary the glyph itself is skipped and a discretionary node
806 -- is output in place of it.
807 local rep, pre, post = glyph.replace, glyph.pre, glyph.post
808
809 setdisc(node, tonodes(pre.head, pre.head, pre.run, pre.glyphs),
810 tonodes(post.head, post.head, post.run, post.glyphs),
811 (tonodes(rep.head, rep.head, rep.run, rep.glyphs)))
812 node = getnext(node)
813 nodeindex = nodeindex + 1
814 else
815 if lastprops and lastprops.zwnj and nodeindex == glyph.cluster + 1 then
816 elseif orig_char then
817 local done
818 local fontglyph = fontglyphs[gid]
819 local character = characters[char]
820
821 if not character.commands then
822 if palette then
823 local layers = fontglyph.layers
824 if layers == nil then
825 layers = hbface:ot_color_glyph_get_layers(gid) or false
826 fontglyph.layers = layers
827 end
828 if layers then
829 local cmds = {} -- Every layer will add 5 cmds
830 local prev_color = nil
831 local k = 1 -- k == j except that k does only get increased if the layer isn't dropped
832 for j = 1, #layers do
833 local layer = layers[j]
834 local layerchar = characters[gid_offset + layer.glyph]
835 if layerchar.height > character.height then
836 character.height = layerchar.height
837 end
838 if layerchar.depth > character.depth then
839 character.depth = layerchar.depth
840 end
841 -- color_index has a special value, 0x10000, that mean use text
842 -- color, we don't check for it here explicitly since we will
843 -- get nil anyway.
844 local color = palette[layer.color_index]
845 if not color or color.alpha ~= 0 then
846 cmds[5*k - 4] = (color and not prev_color) and save_cmd or nop_cmd
847 cmds[5*k - 3] = prev_color == color and nop_cmd or (color and {"pdf", "page", color_to_rgba(color)} or restore_cmd)
848 cmds[5*k - 2] = push_cmd
849 cmds[5*k - 1] = {"char", layer.glyph + gid_offset}
850 cmds[5*k] = pop_cmd
851 fontglyphs[layer.glyph].used = true
852 prev_color = color
853 k = k+1
854 end
855 end
856 cmds[#cmds + 1] = prev_color and restore_cmd
857 if not character.colored then
858 local coloredcharacter = {}
859 for k,v in next, character do
860 coloredcharacter[k] = v
861 end
862 coloredcharacter.commands = cmds
863 local newcharacters = {[gid + 0x130000] = coloredcharacter}
864 characters[gid + 0x130000] = coloredcharacter
865 if char ~= gid + gid_offset then
866 newcharacters[char] = coloredcharacter
867 characters[char] = coloredcharacter
868 character.colored = char
869 else
870 character.colored = gid + 0x130000
871 end
872 font.addcharacters(fontid, {characters = newcharacters})
873 end
874 char = character.colored
875 character = characters[char]
876 end
877 end
878
879 if haspng then
880 local pngglyph = character.pngglyph
881 if pngglyph == nil then
882 local pngblob = hbfont:ot_color_glyph_get_png(gid)
883 if pngblob then
884 local glyphimg = cachedpng(pngblob:get_data())
885 local pngchar = { }
886 for k,v in next, character do
887 pngchar[k] = v
888 end
889 local i = img.copy(glyphimg)
890 i.width = character.width
891 i.depth = 0
892 i.height = character.height + character.depth
893 pngchar.commands = fonttype and {
894 {"push"}, {"char", gid_offset + gid}, {"pop"},
895 {"down", character.depth}, {"image", i}
896 } or { {"down", character.depth}, {"image", i} }
897 if not nominals[gid] then
898 char = 0x130000 + gid
899 end
900 characters[char] = pngchar
901 pngglyph = char
902 font.addcharacters(fontid, {characters = {[char] = pngchar}})
903 end
904 character.pngglyph = pngglyph
905 end
906 if pngglyph then
907 char = pngglyph
908 elseif not fonttype then
909 -- Color bitmap font with no glyph outlines (like Noto
910 -- Color Emoji) but has no bitmap for current glyph (most likely
911 -- `.notdef` glyph). The engine does not know how to embed such
912 -- fonts, so we don't want them to reach the backend as it will cause
913 -- a fatal error. We use `nullfont` instead. That is a hack, but I
914 -- think it is good enough for now. We could make the glyph virtual
915 -- with empty commands such that LuaTeX ignores it, but we still want
916 -- a missing glyph warning.
917 -- We insert the glyph node and move on, no further work is needed.
918 setfont(node, 0)
919 done = true
920 end
921 end
922 end
923 if not done then
924 local oldcharacter = characters[orig_char]
925 -- If the glyph index of current font character is the same as shaped
926 -- glyph, keep the node char unchanged. Helps with primitives that
927 -- take characters as input but actually work on glyphs, like
928 -- `\rpcode`.
929 if not oldcharacter then
930 if gid == 0 then
931 local new = copynode(node)
932 head, node = insertafter(head, node, new)
933 end
934 setchar(node, char)
935 elseif character.commands
936 or character.index ~= oldcharacter.index then
937 setchar(node, char)
938 end
939 local xoffset = (rtl and -glyph.x_offset or glyph.x_offset) * scale
940 local yoffset = glyph.y_offset * scale
941 setoffsets(node, xoffset, yoffset)
942
943 fontglyph.used = fonttype and true
944
945 -- The engine will use this string when printing a glyph node e.g. in
946 -- overfull messages, otherwise it will be trying to print our
947 -- invalid pseudo Unicode code points.
948 -- If the string is empty it means this glyph is part of a larger
949 -- cluster and we don't to print anything for it as the first glyph
950 -- in the cluster will have the string of the whole cluster.
951 local props = properties[node]
952 if not props then
953 props = {}
954 properties[node] = props
955 end
956 props.glyph_info = glyph.string or ""
957
958 -- Handle PDF text extraction:
959 -- * Find how many characters in this cluster and how many glyphs,
960 -- * If there is more than 0 characters
961 -- * One glyph: one to one or one to many mapping, can be
962 -- represented by font's /ToUnicode
963 -- * More than one: many to one or many to many mapping, can be
964 -- represented by /ActualText spans.
965 -- * If there are zero characters, then this glyph is part of complex
966 -- cluster that will be covered by an /ActualText span.
967 local tounicode = glyph.tounicode
968 if tounicode then
969 if glyph.nglyphs == 1
970 and not character.commands
971 and not fontglyph.tounicode then
972 fontglyph.tounicode = tounicode
973 elseif character.commands or tounicode ~= fontglyph.tounicode then
974 setprop(node, startactual_p, tounicode)
975 glyphs[i + glyph.nglyphs - 1].endactual = true
976 end
977 end
978 if glyph.endactual then
979 setprop(node, endactual_p, true)
980 end
981 local x_advance = glyph.x_advance
982 local width = fontglyph.width * hfactor
983 if width ~= x_advance then
984 -- The engine always uses the glyph width from the font, so we need
985 -- to insert a kern node if the x advance is different.
986 local kern = newkern((x_advance - width) * scale, node)
987 head, node = insertkern(head, node, kern, rtl)
988 end
989 end
990 elseif id == glue_t and getsubtype(node) == spaceskip_t then
991 -- If the glyph advance is different from the font space, then a
992 -- substitution or positioning was applied to the space glyph changing
993 -- it from the default. We try to maintain as much as possible from the
994 -- original value because we assume that we want to keep spacefactors and
995 -- assume that we got mostly positioning applied. TODO: Handle the case that
996 -- we became a glyph in the process.
997 -- We are intentionally not comparing with the existing glue width as
998 -- spacing after the period is larger by default in TeX.
999 local width = glyph.x_advance * scale
1000 -- if space > width + 2 or width > space + 2 then
1001 if space ~= width then
1002 setwidth(node, getwidth(node) - space + width)
1003 -- setfield(node, "stretch", width / 2)
1004 -- setfield(node, "shrink", width / 3)
1005 end
1006 elseif id == kern_t and getsubtype(node) == italiccorr_t then
1007 -- If this is an italic correction node and the previous node is a
1008 -- glyph, update its kern value with the glyph's italic correction.
1009 local prevchar, prevfontid = ischar(getprev(node))
1010 if prevfontid == fontid and prevchar and prevchar > 0 then
1011 local italic = characters[prevchar].italic
1012 if italic then
1013 setkern(node, italic)
1014 end
1015 end
1016 end
1017 node = getnext(node)
1018 nodeindex = nodeindex + 1
1019 end
1020 end
1021 while node ~= run.after do
1022 local oldnode = node
1023 head, node = removenode(head, node)
1024 freenode(oldnode)
1025 end
1026
1027 return head, node
1028 end
1029
1030 local function shape_run(head, current, run)
1031 if not run.skip then
1032 -- Font loaded with our loader and an HarfBuzz face is present, do our
1033 -- shaping.
1034 local glyphs, offset
1035 head, current, glyphs, offset = shape(head, current, run)
1036 if glyphs then
1037 return offset, tonodes(head, current, run, glyphs)
1038 end
1039 end
1040 return 0, head, run.after
1041 end
1042
1043 function process(head, font, _attr, direction)
1044 local newhead, runs = itemize(head, font, direction)
1045 local current = newhead
1046
1047 local offset = 0
1048 for i = 1,#runs do
1049 local run = runs[i]
1050 run.start = run.start - offset
1051 local new_offset
1052 new_offset, newhead, current = shape_run(newhead, current, run)
1053 offset = offset + new_offset
1054 end
1055
1056 return newhead or head
1057 end
1058
1059 local function pageliteral(data, base)
1060 local n = inherit(whatsit_t, pdfliteral_t, base, getproperty(base))
1061 setwhatsitfield(n, "mode", 1) -- page
1062 setwhatsitfield(n, "data", data) -- page
1063 return n
1064 end
1065
1066 local function post_process(head)
1067 for n in traverse(head) do
1068 local props = properties[n]
1069
1070 local startactual, endactual
1071 if props then
1072 startactual = rawget(props, startactual_p)
1073 endactual = rawget(props, endactual_p)
1074 end
1075
1076 if startactual then
1077 local actualtext = "/Span<</ActualText<FEFF"..startactual..">>>BDC"
1078 head = insertbefore(head, n, pageliteral(actualtext, n))
1079 props[startactual_p] = nil
1080 end
1081
1082 if endactual then
1083 head = insertafter(head, n, pageliteral("EMC", n))
1084 props[endactual_p] = nil
1085 end
1086
1087 local replace = getfield(n, "replace")
1088 if replace then
1089 setfield(n, "replace", post_process(replace))
1090 end
1091 end
1092 return head
1093 end
1094
1095 local function post_process_vlist(head)
1096 for n, id, subtype, list in traverse_list(head) do
1097 if id == hlist_t and subtype == line_t then
1098 setlist(n, post_process(list))
1099 end
1100 end
1101 return true
1102 end
1103
1104 local function post_process_nodes(head)
1105 return tonode(post_process(todirect(head)))
1106 end
1107
1108 local function post_process_vlist_nodes(head)
1109 return tonode(post_process_vlist(todirect(head)))
1110 end
1111
1112 local function run_cleanup()
1113 -- Remove temporary PNG files that we created, if any.
1114 -- FIXME: It would be nice if we wouldn't need this
1115 if not tmpdirname then return end
1116 for file in dir(tmpdirname) do
1117 if file ~= '.' and file ~= '..' then
1118 assert(osremove(format('%s/%s', tmpdirname, file)))
1119 end
1120 end
1121 assert(rmdir(tmpdirname))
1122 tmpdirname = nil
1123 end
1124
1125 local function set_tounicode()
1126 for fontid, fontdata in font.each() do
1127 local hbdata = fontdata.hb
1128 if hbdata and fontid == pdf.getfontname(fontid) then
1129 local characters = fontdata.characters
1130 local newcharacters = {}
1131 local hbshared = hbdata.shared
1132 local glyphs = hbshared.glyphs
1133 local nominals = hbshared.nominals
1134 local gid_offset = hbshared.gid_offset
1135 for gid = 0, #glyphs do
1136 local glyph = glyphs[gid]
1137 if glyph.used then
1138 local character = characters[gid + gid_offset]
1139 newcharacters[gid + gid_offset] = character
1140 local unicode = nominals[gid]
1141 if unicode then
1142 newcharacters[unicode] = character
1143 end
1144 character.tounicode = glyph.tounicode or unicode or "FFFD"
1145 character.used = true
1146 end
1147 end
1148 font.addcharacters(fontid, { characters = newcharacters })
1149 end
1150 end
1151 end
1152
1153 -- FIXME: Move this into generic parts of luaotfload
1154 local utfchar = utf8.char
1155 local function get_glyph_info(n)
1156 n = todirect(n)
1157 local props = properties[n]
1158 local info = props and props.glyph_info
1159 if info then return info end
1160 local c = getchar(n)
1161 if c == 0 then
1162 return '^^@'
1163 elseif c < 0 then -- These are left and right boundaries in ligature lists
1164 return ''
1165 elseif c < 0x110000 then
1166 return utfchar(c)
1167 else
1168 return string.format("^^^^^^%06X", c)
1169 end
1170 end
1171
1172 fonts.handlers.otf.registerplugin('harf', process)
1173
1174 local add_to_callback = luatexbase.add_to_callback
1175
1176 add_to_callback('post_linebreak_filter', post_process_vlist_nodes, 'luaotfload.harf.finalize_vlist')
1177 add_to_callback('hpack_filter', post_process_nodes, 'luaotfload.harf.finalize_hlist')
1178 add_to_callback('wrapup_run', run_cleanup, 'luaotfload.cleanup_files')
1179 add_to_callback('finish_pdffile', set_tounicode, 'luaotfload.harf.finalize_unicode')
1180 add_to_callback('glyph_info', get_glyph_info, 'luaotfload.glyphinfo')