Debian Codegraph @

texmf-dist/tex/luatex/blopentype/blot-fonts.lua

raw
1 -- *** UTILITY FUNCTIONS ***
2 local function get_locals (tab)
3 local tb = {}
4 for lib, keys in pairs(tab) do
5 keys = string.explode(keys)
6 for _, k in ipairs(keys) do
7 tb[k] = _G[lib][k]
8 end
9 end
10 return tb
11 end
12
13 -- str
14 -- string manipulation
15 local str = get_locals {string = "explode gsub match format lower upper"}
16
17 -- Removes space at the beginning and end and conflates multiple spaces.
18 function str.trim (s)
19 s = str.match(s, "^%s*(.-)%s*$")
20 s = str.gsub(s, "%s+", " ")
21 return s
22 end
23
24 -- Extracts a pattern from a string, i.e. removes it and returns it.
25 -- If "full", then the entire pattern is removed, not only the captures.
26 function str.extract (s, pat, full)
27 local cap = str.match(s, pat)
28 if cap then
29 if full then
30 s = str.gsub(s, pat, "")
31 else
32 s = str.gsub(s, cap, "")
33 end
34 end
35 return cap, s
36 end
37 -- /str
38
39
40 -- lp
41 -- advanced string manipulation
42 lpeg.locale(lpeg)
43 local lp = get_locals {lpeg = "match P C S Ct V alnum"}
44 lp.space = lpeg.space^0
45 -- /lp
46
47
48 -- tab
49 -- table manipulation
50 local tab = get_locals {table = "insert remove sort"}
51
52 -- Adds val to tab, creating it if necessary.
53 function tab.update (tb, val)
54 tb = tb or {}
55 tab.insert(tb, val)
56 return tb
57 end
58
59 -- Adds subtable (empty, or val) to tb at entry key, unless it already exists.
60 function tab.subtable (tb, key, val)
61 tb[key] = tb[key] or val or {}
62 end
63
64 -- Writes a table to an extenal file.
65 local function write_key (key, ind)
66 return ind .. '["' .. key .. '"] = '
67 end
68
69 function tab.write (tb, f, ind)
70 for a, b in pairs (tb) do
71 if type(a) == "string" then
72 a = '"' .. a .. '"'
73 end
74 a = "[" .. a .. "]"
75 if type(b) == "table" then
76 f:write(ind, a, " = {")
77 tab.write(b, f, ind .. " ")
78 f:write(ind, "},")
79 else
80 if type(b) == "boolean" then
81 b = b and "true" or "false"
82 elseif type(b) == "string" then
83 b = '"' .. b .. '"'
84 end
85 f:write(ind, a, " = ", b, ",")
86 end
87 end
88 end
89
90 -- Returns a full copy of a table. Not copying of metatables necessary for the
91 -- moment.
92 function tab.copy (tb)
93 local t = {}
94 for k, v in pairs (tb) do
95 if type(v) == "table" then
96 v = tab.copy(v)
97 end
98 t[k] = v
99 end
100 return t
101 end
102
103 -- Sorts two tables containing modifiers (Italic, etc.).
104 function tab.sortmods (a, b)
105 local A, B = "", ""
106 for _, x in ipairs (a) do
107 A = A .. " " .. x
108 end
109 for _, x in ipairs (b) do
110 B = B .. " " .. x
111 end
112 return A < B
113 end
114
115 -- Turns an array into a hash.
116 function tab.tohash(tb)
117 local t = {}
118 for _, k in ipairs(tb) do
119 t[k] = true
120 end
121 return t
122 end
123 -- /tab
124
125 -- lfs
126 -- files etc.
127 local lfs = get_locals {lfs = "dir isdir isfile mkdir", kpse = "expand_var show_path find_file"}
128
129 -- Returns anything after the last dot, i.e. an extension.
130 function lfs.extension (s)
131 return str.lower(str.match(s, "%.([^%.]*)$") or "")
132 -- return str.match(s, "%.([^%.]*)$") -- bugfix: dpc for empty field in file extension 230902
133 end
134
135 local extensions = {
136 otf = "opentype",
137 ttf = "truetype",
138 ttc = "truetype",
139 }
140 function lfs.type (s)
141 return extensions[lfs.extension(s)]
142 end
143
144 local kpse_extensions = {
145 otf = "opentype fonts",
146 ttf = "truetype fonts",
147 ttc = "truetype fonts",
148 }
149 function lfs.kpse (s)
150 return kpse_extensions[lfs.extension(s)]
151 end
152
153 -- Returns anything after the last slash, i.e. a pathless file.
154 function lfs.nopath (f)
155 return str.match(f, "[^/]*$")
156 end
157
158 -- Creates a directory; the arguments are the successive subdirectories.
159 function lfs.ensure_dir (...)
160 local arg, path = {...}
161 for _, d in ipairs(arg) do
162 if path then
163 path = path .. "/" .. d
164 else
165 path = d
166 end
167 path = str.gsub(path, "//", "/")
168 if not lfs.isdir(path) then
169 lfs.mkdir(path)
170 end
171 end
172 return path
173 end
174
175 -- Turns "foo/blahblah/../" into "foo/" (such going into and leaving
176 -- directories happens with kpse). Also puts everything to lowercase.
177 function lfs.smooth_file (f)
178 f = str.gsub(f, "/.-/%.%./", "/")
179 f = str.gsub(f, "^%a", str.lower)
180 return f
181 end
182 -- /lfs
183
184
185 -- wri
186 -- messages
187 local wri, write_nl = {}, texio.write_nl
188
189 function wri.report (s, ...)
190 -- write_nl(str.format(s, unpack(arg)))
191 end
192
193 function wri.error (s, ...)
194 -- tex.error(str.format(s, unpack(arg)))
195 end
196 -- /wri
197
198
199 -- various
200 -- the last one is, of course, not the least
201 local io = get_locals {io = "open lines"}
202 local os = get_locals {os = "date"}
203 local num = get_locals {math = "abs tan rad floor pi", tex = "sp"}
204 local fl = get_locals {fontloader = "open close to_table info", font = "read_tfm"}
205 -- /various
206
207
208 -- *** END OF UTILITY FUNCTIONS ***
209
210
211
212 --- *** CREATING THE LIBRARY *** ---
213 local settings
214 if lfs.find_file"blot-sets.lua" then
215 settings = require"blot-sets.lua"
216 else
217 settings = {normal = {}, features = {}}
218 end
219 local font_families = {}
220 local normal_names = {}
221 for _, name in ipairs(settings.normal) do
222 normal_names[name] = true
223 end
224 local local_path = lfs.expand_var("$TEXMFLOCAL")
225 -- local local_path = lfs.expand_var("$TEXMFHOME") -- :gsub(":",";") -- bugfix dpc: no path search gsub 0.0.2
226 local foundry_path = lfs.ensure_dir (local_path, "tex", "luatex", "blotfonts")
227 -- local foundry_path = lfs.ensure_dir (local_path, "fonts", "truetype", "public", "gfs")
228 local library_file = foundry_path .. "/" .. "readable.txt"
229 -- local library_file = "c:/texlive/texmf-local/tex/plain/pitex/readable.txt"
230 -- local library_file = "readable.txt"
231
232 -- Analyze a font file and return a name and a table
233 -- with modifiers.
234 local function extract_font (file, names)
235 local fi, subname
236 -- Trying to open a font in ttc, using the names returned by fontloader.info
237 if names then
238 local name = names.fullname
239 if name then
240 fi = fl.open (file, name)
241 end
242 if not fi then
243 name = names.fontname
244 if name then
245 fi = fl.open
246 end
247 if not fi then
248 -- fl.error("Can't open %s", file)
249 fl.error("\nCannot open file", file)
250 return
251 end
252 end
253 subname = name
254 else
255 fi = fl.open(file)
256 -- blot-fonts.lua:257: attempt to index a nil value (local 'fi')
257 if not fi then
258 print("\nCannot open file", file)
259 return
260 end
261 end
262 -- Getting the most precise information. Not necessarily the best
263 -- solution, but since the user can modify the library, it's not so bad.
264 local fam, name = fi.names[1].names.preffamilyname or fi.names[1].names.family or fi.familyname, fi.fontname
265 local spec = fi.names[1].names.prefmodifiers or fi.names[1].names.subfamily or ""
266 local subfam, _spec
267 local t = { [0] = file }
268 -- Removing mods like Regular, Book, etc.
269 for name in pairs(normal_names) do
270 spec = str.gsub(spec, name, "")
271 end
272 if subname then
273 tab.insert(t, "[font = " .. subname .. "]")
274 end
275 if spec ~= "" then
276 spec = str.explode(spec)
277 for _, s in ipairs(spec) do
278 tab.insert(t, s)
279 end
280 end
281 fl.close(fi)
282 return fam, t
283 end
284
285 -- Searches directories for font files, and pass them to
286 -- extract_font. The fonts are collected in a table.
287 -- The fonts_done table is updated when the library is read,
288 -- so when a font is missing and one needs to recheck files,
289 -- only those that arent in the libraries are considered.
290 local fonts_done = {}
291 local function check_fonts (rep, tb)
292 if lfs.isdir(rep) then
293 for f in lfs.dir (rep) do
294 if f ~= "." and f ~= ".." then
295 f = str.gsub(rep, "/$", "") .. "/" .. f
296 if lfs.isdir(f) then
297 check_fonts(f, tb)
298 elseif lfs.isfile(f) and not fonts_done[lfs.nopath(f)] then
299 local e = lfs.extension(f)
300 if e == "ttf" or e == "otf" then
301 local fam, file = extract_font(f)
302 if fam then
303 tab.subtable(tb, fam)
304 tab.insert(tb[fam], file)
305 end
306 elseif e == "ttc" then
307 local info = fl.info(f)
308 for _, i in ipairs(info) do
309 local fam, file = extract_font(f, i)
310 if fam then
311 tab.subtable(tb, fam)
312 tab.insert(tb[fam], file)
313 end
314 end
315 end
316 end
317 end
318 end
319 end
320 end
321
322 -- Writes the library to an external file.
323 -- Type is "a" if what's going on is recheck_fonts.
324 local function write_lib (fams, file, type)
325 local read_table = {}
326 for fam, tb in pairs(fams) do
327 tab.insert(read_table, fam)
328 for _, ttb in ipairs(tb) do
329 tab.sort(ttb)
330 end
331 tab.sort(tb, tab.sortmods)
332 end
333 tab.sort(read_table)
334 local readable = io.open(file, type)
335 for n, fam in ipairs(read_table) do
336 local log
337 if type == "a" then
338 log = true
339 if n == 1 then
340 wri.report("\nAdding new font(s):")
341 readable:write("\n\n% Added automatically " .. os.date() .. "\n\n")
342 end
343 wri.report(fam)
344 end
345 readable:write(fam .. " :")
346 for n, f in ipairs(fams[fam]) do
347 log = log and " "
348 readable:write("\n ")
349 for _, t in ipairs(f) do
350 log = log and log .. " " .. t
351 readable:write(" " .. t)
352 end
353 log = log and log .. " " .. '"' .. f[0] .. '"'
354 readable:write(" " .. '"' .. lfs.nopath(f[0]) .. '",')
355 if log then wri.report(log) end
356 if n == #fams[fam] then
357 readable:write("\n\n")
358 end
359 end
360 end
361 readable:close()
362 end
363
364
365 -- If there is no library, we create it.
366 local font_paths = lfs.show_path("opentype fonts")
367 font_paths = str.gsub(font_paths, ":", ";")
368 font_paths = str.gsub(font_paths, "\\", "/")
369 font_paths = str.gsub(font_paths, "/+", "/")
370 font_paths = str.gsub(font_paths, "!!", "")
371 font_paths = str.explode(font_paths, ";+")
372
373 if not lfs.find_file(library_file) then
374 wri.report("I must create the library; please wait, that can take some time.")
375 for _, rep in ipairs(font_paths) do
376 check_fonts(rep, font_families)
377 end
378 write_lib(font_families, library_file, "w")
379 end
380
381 -- Reads the library file, turning it into a table.
382 local explode_semicolon = lp.P{
383 lp.Ct(lp.V"data"^1),
384 data = lp.C(((1 - lp.S";[") + (lp.S"[" * (1 - lp.S"]")^0 * lp.S"]" ))^1) / str.trim * (lp.S";" + -1),
385 }
386 local explode_comma = lp.P{
387 lp.Ct(lp.V"data"^1),
388 data = lp.C(((1 - lp.S",[") + (lp.S"[" * (1 - lp.S"]")^0 * lp.S"]" ))^1) / str.trim * (lp.S"," + -1),
389 }
390
391 local function load_library (lib)
392 local LIB = ""
393 local lib_file = lfs.find_file(lib)
394 if not lib_file then
395 wri.error("I can't find library %s.", lib)
396 return
397 end
398
399 for l in io.lines(lib_file) do
400 if not str.match(l, "^%s*%%") then
401 if str.match(l, "^%s*$") then
402 LIB = LIB .. ";"
403 else
404 LIB = LIB .. " " .. l
405 end
406 end
407 end
408 LIB = str.gsub(LIB, ";%s*;", ";;")
409 LIB = str.gsub(LIB, ";+", ";")
410 LIB = str.gsub(LIB, "^;", "")
411 LIB = str.gsub(LIB, ":%s*:", "::")
412 LIB = str.gsub(LIB, ":+", ":")
413 LIB = str.gsub(LIB, "^:", "")
414 LIB = str.gsub(LIB, "%s+", " ")
415
416 LIB = lp.match(explode_semicolon, LIB)
417
418 local newlib = {}
419 for _, t in ipairs(LIB) do
420 local fam, files = str.match(t, "(.-):(.*)")
421 local current_mods
422 if files then
423 files = lp.match(explode_comma, files)
424 fam = str.explode(fam, ",")
425 local root
426 for n, f in ipairs (fam) do
427 f = str.trim(f)
428 if n == 1 then
429 root = f
430 if type(newlib[f]) == "string" then
431 wri.error("Name `%s' is already used as an alias for `%s'; it is now overwritten to denote a family", f, newlib[f])
432 newlib[f] = {}
433 else
434 newlib[f] = newlib[f] or {}
435 end
436 else
437 if newlib[f] then
438 wri.error("The name `%s' is already used. I ignore it as an alias for `%s'", f, root)
439 else
440 newlib[f] = root
441 end
442 end
443 end
444 for _, f in ipairs(files) do
445 local reset
446 reset, f = str.extract(f, "^%.%.", true)
447 if reset then current_mods = nil end
448 local mods, file, feats = str.match(f, '([^"]*)"(.*)"')
449 if mods then
450 fonts_done[lfs.nopath(file)] = true
451 feats, mods = str.extract(mods, "%[([^%]]-)]", true)
452 mods = str.explode(mods)
453 if current_mods then
454 for _, t in ipairs(current_mods) do
455 tab.insert(mods, t)
456 end
457 if current_mods.feats then
458 feats = feats or ""
459 feats = current_mods.feats .. "," .. feats
460 end
461 end
462 local sizes, real_mods = {}, {}
463 for n, s in ipairs(mods) do
464 if tonumber(s) then
465 tab.insert(sizes, tonumber(s))
466 else
467 tab.insert(real_mods, s)
468 end
469 end
470 sizes = #sizes > 0 and sizes or {0}
471 tab.sort(real_mods)
472 local T = newlib[root]
473 for _, t in ipairs(real_mods) do
474 t = str.trim(t)
475 if t ~= "" then
476 T[t] = T[t] or {}
477 T = T[t]
478 end
479 end
480 T.__files = T.__files or {}
481 for _, s in ipairs(sizes) do
482 T.__files[s] = {str.trim(file), feats}
483 end
484 else
485 feats, mods = str.extract(f, "%[([^%]]-)]", true)
486 if current_mods then
487 for _, mod in ipairs(str.explode(mods)) do
488 tab.insert(current_mods, mod)
489 end
490 if feats then
491 current_mods.feats = current_mods.feats and current_mods.feats .. "," .. feats or feats
492 end
493 else
494 current_mods = str.explode(mods)
495 current_mods.feats = feats
496 end
497 end
498 end
499 end
500 end
501 return newlib
502 end
503
504 local library = {}
505 library.default = load_library(library_file)
506
507 -- Same as above, but used when rechecking (if a font isn't found in libraries).
508 local function recheck_fonts ()
509 local tb = {}
510 for _, rep in ipairs(font_paths) do
511 check_fonts(rep, tb)
512 end
513 write_lib(tb, library_file, "a")
514 library.default = load_library(library_file)
515 end
516
517
518 -- This is public.
519 function new_library (lib)
520 local l = load_library(lib)
521 if l then
522 tab.insert(library, l)
523 end
524 end
525
526 --- *** END OF LIBRARY MANAGEMENT *** ---
527
528
529
530 --- *** FONT CREATION *** ---
531
532
533 -- Creates a new substitution for trep.
534 local function add_sub (f, num, sub)
535 num, sub = f.map.map[num], f.map.map[sub]
536 if f.glyphs[num] and f.glyphs[sub] then
537 local x = f.glyphs[num]
538 tab.subtable(x, "lookups")
539 x.lookups.tex_trep = { { type = "substitution", specification = {variant = f.glyphs[sub].name} } }
540 end
541 end
542
543 -- Creates a new ligature for tlig.
544 local function add_lig (f, lig, ...)
545 lig = f.map.map[lig]
546 if lig then
547 arg = {...}
548 local components
549 for _, c in ipairs(arg) do
550 c = f.map.map[c]
551 c = c and f.glyphs[c]
552 if c then
553 c = c.name
554 components = components and components .. " " .. c or c
555 else
556 components = nil
557 break
558 end
559 end
560 if components then
561 local x = f.glyphs[lig]
562 tab.subtable(x, "lookups")
563 tab.subtable(x.lookups, "tex_tlig")
564 tab.insert(x.lookups.tex_tlig, { type = "ligature",
565 specification = {char = x.name, components = components} })
566 end
567 end
568 end
569
570 -- Loops over all the constitutents of ligatures, creating intermediary
571 -- ligatures if necessary. E.g. "f f i" is broken into:
572 -- f + f = ff.lig
573 -- ff.lig + i = ffi.lig
574 -- Then when loading the font if the intermediary ligatures do not exist
575 -- (e.g. "1/" in "1 / 4") a phantom character is added to the font; which might
576 -- be dangerous (e.g. "1/" will create a node without character if no "4" follows).
577 -- The ".lig" suffix is arbitrary but all glyphs marked as ligatures are also registered
578 -- with such a name, so if there's an "f f" ligature in a font, no matter its name, "ff.lig"
579 -- will point to it.
580 local function ligature (comp, tb, phantoms)
581 if #tb == 0 then -- fast kludge to evade empty tables. jlrn 231207
582 else
583 local i = str.gsub(comp[1], "%.lig$", "") .. comp[2] .. ".lig"
584 phantoms[i] = true
585 tab.insert(tb.all_ligs, i)
586 tab.subtable(tb, comp[1])
587 tb[comp[1]][comp[2]] = { char = i, type = 0 } -- The type could be something else.
588 tab.remove(comp, 1)
589 tab.remove(comp, 1)
590 if #comp > 0 then
591 tab.insert(comp, 1, i)
592 ligature(comp, tb, phantoms)
593 end
594 end -- endkludge 231209
595 end
596
597 local function get_lookups (t, lookup_table)
598 if t then
599 for _, tb in pairs(t) do
600 local _tb = { tags = {} }
601 if tb.features then
602 for _, feats in pairs(tb.features) do
603 local _tag = {}
604 if feats.scripts then
605 for _, scr in pairs(feats.scripts) do
606 _tag[scr.script] = {}
607 for _, lang in pairs(scr.langs) do
608 tab.insert (_tag[scr.script], str.trim(lang))
609 end
610 end
611 end
612 for _, sub in pairs(tb.subtables) do
613 tab.insert(_tb, sub.name)
614 end
615 _tb.tags[feats.tag] = _tag
616 end
617 end
618 if tb.name then
619 local tp = tb.type or "no_type"
620 tab.subtable(lookup_table, tp)
621 lookup_table[tp][tb.name] = _tb
622 end
623 end
624 end
625 end
626
627 function create_font (filename, extension, path, subfont, write)
628
629 local data = fl.open(filename, subfont)
630 fontfile = fl.to_table(data)
631 fl.close(data)
632
633 local lookups = {}
634
635 local name_touni = { }
636 local max_char = 0
637 for chr, gly in pairs(fontfile.map.map) do
638 max_char = chr > max_char and chr or max_char
639 -- Some glyphs have the same name in some fonts,
640 -- e.g. the several hyphens.
641 local name = fontfile.glyphs[gly].name
642 while name_touni[name] do
643 name = name .. "_"
644 end
645 name_touni[name] = chr
646 end
647
648 if fontfile.gsub then
649 tab.insert(fontfile.gsub,
650 { type = "gsub_single",
651 name = "tex_trep",
652 subtables = { {name = "tex_trep"} },
653 features = { { tag = "trep"} } })
654 tab.insert(fontfile.gsub,
655 { type = "gsub_ligature",
656 name = "tex_tlig",
657 subtables = { {name = "tex_tlig"} },
658 features = { { tag = "tlig"} } })
659 for _, tb in ipairs(fontfile.gsub) do
660 for __, ttb in ipairs(tb.subtables) do
661 if tb.type == "gsub_contextchain" then
662 lookups[tb.name] = lookups[tb.name] or { type = tb.type }
663 tab.insert(lookups[tb.name], ttb.name)
664 end
665 lookups[ttb.name] = { type = tb.type }
666 lookups["-" .. ttb.name] = { type = tb.type }
667 end
668 end
669 end
670
671 if fontfile.gpos then
672 for _, tb in ipairs(fontfile.gpos) do
673 for __, ttb in ipairs(tb.subtables) do
674 lookups[ttb.name] = { type = tb.type }
675 lookups["-" .. ttb.name] = { type = tb.type }
676 end
677 end
678 end
679
680 if fontfile.kerns then
681 for _, class in ipairs(fontfile.kerns) do
682 local max = 0
683 for a in pairs (class.seconds) do
684 max = max < a and a or max
685 end
686 if type(class.lookup) == "string" then
687 lookups[class.lookup] = { type = "gpos_pair", firsts = class.firsts, seconds = class.seconds, offsets = class.offsets, max = max}
688 else
689 for _, lk in ipairs(class.lookup) do
690 lookups[lk] = { type = "gpos_pair", firsts = class.firsts, seconds = class.seconds, offsets = class.offsets, max = max}
691 end
692 end
693 end
694 end
695
696 add_sub(fontfile, 96, 8216) -- ` to quoteleft
697 add_sub(fontfile, 39, 8217) -- ' to apostrophe (quoteright)
698
699 add_lig(fontfile, 8220, 8216, 8216) -- quoteleft + quoteleft to quotedblleft
700 add_lig(fontfile, 8221, 8217, 8217) -- quoteright + quoteright to quotedblright
701 add_lig(fontfile, 8211, 45, 45) -- -- to endash
702 add_lig(fontfile, 8212, 8211, 45) -- --- (i.e. endash + -) to emdash
703 add_lig(fontfile, 161, 63, 96) -- ?` to inverted question mark
704 add_lig(fontfile, 161, 63, 8216) -- The same, with `turned to quoteleft.
705 add_lig(fontfile, 191, 33, 96) -- !` to inverted exclamation mark
706 add_lig(fontfile, 191, 33, 8216) -- Idem.
707
708 local characters, phantom_ligatures = {}, {}
709 for chr, gly in pairs(fontfile.map.map) do
710 local glyph, char = fontfile.glyphs[gly], {}
711
712 char.index = gly
713 char.name = glyph.name
714 char.width = glyph.width
715 if glyph.boundingbox then
716 char.depth = -glyph.boundingbox[2]
717 char.height = glyph.boundingbox[4]
718 end
719 if glyph.italic_correction then
720 char.italic = glyph.italic_correction
721 elseif glyph.width and glyph.boundingbox then
722 char.italic = glyph.boundingbox[3] - glyph.width
723 end
724 tab.subtable(characters, chr)
725 characters[chr] = char
726
727 if glyph.lookups then
728 for lk, tb in pairs(glyph.lookups) do
729 local _lk = "-" .. lk
730 if lookups[lk] and lookups[_lk] then
731 for _, l in ipairs(tb) do
732 if l.type == "substitution" then
733
734 tab.subtable(lookups[lk], "pairs")
735 lookups[lk].pairs[glyph.name] = l.specification.variant
736
737 tab.subtable(lookups[_lk], "pairs")
738 lookups[_lk].pairs[l.specification.variant] = glyph.name
739
740 elseif l.type == "ligature" then
741
742 local comp, lig = str.explode(l.specification.components), l.specification.char
743 local lig = ""
744 for _, c in ipairs(comp) do
745 lig = lig .. c
746 end
747
748 tab.subtable(lookups, lk)
749 tab.subtable(lookups[lk], "ligs", {all_ligs = {}})
750 ligature(comp, lookups[lk].ligs, phantom_ligatures)
751 name_touni[lig .. ".lig"] = chr
752
753 end
754 end
755 end
756 end
757 end
758
759 if glyph.kerns then
760 for _, kern in pairs(glyph.kerns) do
761 local lks = type(kern.lookup) == "table" and kern.lookup or {kern.lookup}
762 for _, lk in ipairs(lks) do
763 tab.subtable(lookups[lk], "kerns")
764 tab.subtable(lookups[lk].kerns, glyph.name)
765 lookups[lk].kerns[glyph.name][kern.char] = kern.off
766 end
767 end
768 end
769
770 end
771
772 for lig in pairs(phantom_ligatures) do
773 if not name_touni[lig] then
774 max_char = max_char + 1
775 name_touni[lig] = max_char
776 characters[max_char] = {name = lig}
777 end
778 end
779
780 local lookup_table = {}
781 get_lookups(fontfile.gsub, lookup_table)
782 get_lookups(fontfile.gpos, lookup_table)
783 get_lookups(fontfile.lookups, lookup_table, true)
784
785 if fontfile.lookups then
786 for name, lk in pairs(fontfile.lookups) do
787 local tb, format = {}, lk.format
788 for _, rule in ipairs(lk.rules) do
789 local ttb = { lookups = rule.lookups }
790 for pos, seq in pairs(rule[format]) do
791 ttb[pos] = {}
792 for _, glyfs in ipairs(seq) do
793 glyfs = str.explode(glyfs)
794 glyfs = tab.tohash(glyfs)
795 tab.insert(ttb[pos], glyfs)
796 end
797 end
798 tab.insert(tb, ttb)
799 end
800 lookups[name] = tb
801 end
802 end
803
804 local loaded_font = {
805
806 direction = 0,
807 filename = filename,
808 format = extension,
809 fullname = fontfile.names[1].names.fullname,
810 name = fontfile.fontname,
811 psname = fontfile.fontname,
812 type = "real",
813 units_per_em = fontfile.units_per_em,
814
815 auto_expand = true,
816
817 cidinfo = fontfile.cidinfo,
818
819 -- Used only to adjust absoluteslant.
820 italicangle = -fontfile.italicangle,
821 name_to_unicode = name_touni,
822 max_char = max_char,
823 lookups = lookups,
824 lookup_table = lookup_table,
825 characters = characters
826 }
827
828 if write then
829 local f = io.open(path, "w")
830 f:write("return {")
831 tab.write(loaded_font, f, "\n")
832 f:write("}")
833 f:close()
834 end
835
836 return loaded_font
837
838 end
839
840 -- GETTING A FONT
841
842 -- Finds a font file, and returns the original
843 -- file and the Lua version.
844 local name_luafile, get_features
845 local function is_font (name, mods, size)
846
847 local lib, library_filename
848 for l, t in ipairs(library) do
849 if t[name] then
850 library_filename = t[name]
851 lib = t
852 break
853 end
854 end
855 if not library_filename then
856 library_filename = library.default[name]
857 lib = library.default
858 end
859
860 if library_filename then
861 if type(library_filename) == "string" then
862 library_filename = lib[library_filename]
863 end
864 tab.sort(mods)
865 local T = library_filename
866 for _, t in ipairs(mods) do
867 local found
868 for tag in pairs(T) do
869 if str.match(tag, "^" .. t) then
870 T = T[tag]
871 found = true
872 break
873 end
874 end
875 if not found then
876 T = nil
877 break
878 end
879 end
880
881 if T and T.__files then
882 local file, feats
883 local diff = 10000
884 for s, f in pairs(T.__files) do
885 if num.abs(s - size) < diff then
886 diff = num.abs(s - size)
887 file, feats = f[1], f[2]
888 end
889 end
890 file, _file = lfs.find_file(file, lfs.kpse(file)), file
891 if file then
892 file = str.gsub(file, "\\", "/")
893 else
894 return 1, _file
895 end
896 local features = {}
897 if feats then
898 get_features(feats, features)
899 end
900 local lua = name_luafile(file, features.font)
901 lua = lfs.isfile(lua) and lua
902 return file, lua, feats
903 end
904 end
905 end
906
907 -- Returns the full path to the Lua version of the font.
908 -- "sub" is a font in ttc.
909 function name_luafile (file, sub)
910 local lua
911 sub = sub and "_" .. sub or ""
912 sub = str.gsub(sub, " ", "_")
913 if str.match(file, "/") then
914 lua = str.match(file, ".*/(.-)%....$")
915 else
916 lua = str.match(file, "(.-)%....$")
917 end
918 lua = lua .. sub
919 return foundry_path .. "/" .. lua .. ".lua"
920 end
921
922 local function apply_size (font, size, letterspacing, parameters)
923 if (size < 0) then size = (- 655.36) * size end
924 local to_size = size / font.units_per_em
925 font.size = size
926 font.designsize = size
927 font.to_size = to_size
928 local italic = font.italicangle or 0
929 local space, stretch, shrink, extra
930 if parameters == "mono" then -- Creates a monospaced font with space equal to the
931 -- width of an "m" and no stretch or shrink.
932 space = font.characters[109].width * to_size
933 stretch, shrink, extra = 0, 0, 0
934 else
935 parameters = parameters and str.explode(parameters) or {}
936 space = (parameters[1] or 0.25) * size
937 stretch = (parameters[2] or 0.166666) * size
938 shrink = (parameters[3] or 0.111111) * size
939 extra = (parameters[4] or 0.111111) * size
940 end
941 font.parameters = {
942 slant = size * num.floor(num.tan(italic * num.pi/180)), -- \fontdimen 1
943 space = space, -- \fontdimen 2
944 space_stretch = stretch, -- \fontdimen 3
945 space_shrink = shrink, -- \fontdimen 4
946 x_height = size * 0.4, -- \fontdimen 5
947 quad = size, -- \fontdimen 6
948 extra_space = extra -- \fontdimen 7
949 }
950
951 letterspacing = letterspacing or 1
952 for c, t in pairs(font.characters) do
953 if t.width then
954 t.width, t.height, t.depth = t.width * to_size * letterspacing, t.height * to_size, t.depth * to_size
955 t.expansion_factor = 1000
956 if t.italic then
957 t.italic = t.italic * to_size
958 end
959 end
960 end
961
962 return font
963 end
964
965
966 local get_mods = lp.Ct((lp.space * lp.S"/" * lp.C(lp.alnum^1))^0)
967 local get_feats = lp.Ct((lp.C((1 - lp.S",;")^1) * (lp.S",;" + -1))^1)
968 function get_features (features, tb)
969 features = lp.match(get_feats, features) or {}
970 for _, f in ipairs(features) do
971 if str.match(f, "=") then
972 local key, val = str.match(f, "%s*(.-)%s*=%s*(.*)")
973 val = str.trim(val)
974 if val == "false" then
975 tb[key] = nil
976 else
977 tb[key] = val
978 end
979 else
980 f = str.trim(f)
981 neg, f = str.extract(f, "^%-")
982 if neg then
983 tb[f] = nil
984 else
985 _, f = str.extract(f, "^%+")
986 tb[f] = true
987 end
988 end
989 end
990 end
991
992 local lookup_functions = {}
993
994 function lookup_functions.gsub_single (tb, f)
995 local name_touni = f.name_to_unicode
996 for a, b in pairs(tb.pairs) do
997 local _a, _b = name_touni[a], name_touni[b]
998 f.max_char = f.max_char + 1
999 f.characters[f.max_char] = f.characters[_a]
1000 f.characters[_a] = f.characters[_b]
1001 name_touni[a], name_touni[b] = f.max_char, _a
1002 end
1003 return f
1004 end
1005
1006 function lookup_functions.gsub_ligature (tb, f)
1007 local name_touni = f.name_to_unicode
1008 tb.ligs.all_ligs = nil
1009 for a, tb in pairs(tb.ligs) do
1010 a = name_touni[a]
1011 tab.subtable(f.characters[a], "ligatures")
1012 for b, ttb in pairs(tb) do
1013 b, c = name_touni[b], name_touni[ttb.char]
1014 f.characters[a].ligatures[b] = {char = c, type = ttb.type}
1015 end
1016 end
1017 return f
1018 end
1019
1020 local function kern_pairs (tb, firsts, seconds, offset)
1021 for _, c1 in ipairs(str.explode(firsts)) do
1022 for __, c2 in ipairs(str.explode(seconds)) do
1023 tab.subtable(tb, c1)
1024 tb[c1][c2] = offset
1025 end
1026 end
1027 end
1028
1029 local function kern_classes (firsts, seconds, offsets, max)
1030 local kerns = {}
1031 for f, F in pairs (firsts) do
1032 for s, S in pairs (seconds) do
1033 local off = offsets[(f-1) * max + s]
1034 if off then
1035 kern_pairs (kerns, F, S, off)
1036 end
1037 end
1038 end
1039 return kerns
1040 end
1041
1042 local function apply_kerns (f, kerns, to_size)
1043 local name_touni = f.name_to_unicode
1044 to_size = to_size or 1
1045 for c1, ttb in pairs(kerns) do
1046 for c2, off in pairs(ttb) do
1047 tab.subtable(f.characters[name_touni[c1]], "kerns")
1048 f.characters[name_touni[c1]].kerns[name_touni[c2]] = off * to_size
1049 end
1050 end
1051 end
1052
1053 function lookup_functions.gpos_pair (tb, f)
1054 -- These are the big kern classes.
1055 if tb.offsets then
1056 local name_touni = f.name_to_unicode
1057 for n, off in pairs(tb.offsets) do
1058 tb.offsets[n] = off * f.to_size
1059 end
1060 local kerns = kern_classes(tb.firsts, tb.seconds, tb.offsets, tb.max)
1061 apply_kerns(f, kerns)
1062 end
1063 -- These are the ones retrieved from individual glyphs.
1064 if tb.kerns then
1065 apply_kerns(f, tb.kerns, f.to_size)
1066 end
1067 return f
1068 end
1069
1070 function lookup_functions.gsub_contextchain (tb, f)
1071 local name_touni = f.name_to_unicode
1072 local T = f.contextchain or {}
1073 for _, llk in ipairs(tb) do
1074 if fontfile.lookups then
1075 local sub, Sub = fontfile.lookups[llk].rules[1].lookups
1076 local chain = fontfile.lookups[llk].rules[1].coverage
1077 local cur, current = str.explode(chain.current[1]), {}
1078 local aft, after = chain.after and str.explode(chain.after[1]) or {}, {}
1079 for _, c in ipairs(cur) do
1080 c = name_touni[c]
1081 if sub then
1082 Sub = {}
1083 for n, x in ipairs(sub) do
1084 Sub[n] = name_touni[fontfile.glyphs[f.characters[c].index].lookups[x .. "_s"][1].specification.variant]
1085 end
1086 end
1087 local t = { lookup = Sub}
1088 tab.subtable(T, C)
1089 for __, a in ipairs(aft) do
1090 tab.subtable(t, "after")
1091 t.after[name_touni[a]] = true
1092 end
1093 tab.insert(T[c], t)
1094 end
1095 end
1096 end
1097 f.contextchain = T
1098 return f
1099 end
1100
1101 local function _isactive (tb, ft, sc, lg)
1102 for t in pairs(tb.tags) do
1103 if ft[t] then
1104 if t[sc] then
1105 for _, lang in pairs(tb[sc]) do
1106 if lang == lg then
1107 return true
1108 end
1109 end
1110 else
1111 return true
1112 end
1113 end
1114 end
1115 end
1116
1117
1118 local lookup_types = {
1119 "gsub_single",
1120 "gsub_ligature",
1121 "gpos_pair"
1122 }
1123
1124 local function activate_lookups (font, features, script, lang)
1125 for _, type in ipairs(lookup_types) do
1126 if font.lookup_table and font.lookup_table[type] then
1127 for l, tb in pairs(font.lookup_table[type]) do
1128 if _isactive(tb, features, script, lang) then
1129 for _, lk in ipairs(tb) do
1130 local lt = font.lookups[lk]
1131 if lt then
1132 font = lookup_functions[type](lt, font)
1133 end
1134 end
1135 end
1136 end
1137 end
1138 end
1139 return font
1140 end
1141
1142 local function load_font (name, size, id, done)
1143 local loaded_font = lfs.find_file(name, "tfm")
1144 if loaded_font then
1145 loaded_font = fl.read_tfm(loaded_font, size)
1146 else
1147 local original = str.trim(str.match(name, "[^:]*"))
1148 local family, mods, feats
1149 family, name = str.extract(name, "([^/:]*)")
1150 family = str.trim(family)
1151 mods, name = str.extract(name, "[^:]*")
1152 mods = lp.match(get_mods, mods) or {}
1153 feats = str.extract(name, ":(.*)") or ""
1154 local features = tab.copy(settings.features)
1155 get_features(feats, features)
1156
1157 local at_size
1158 if features.size then
1159 at_size = features.size
1160 else
1161 at_size = size
1162 at_size = at_size > 0 and at_size or at_size * - 655.36
1163 at_size = at_size / 65536
1164 end
1165 local source, lua, add_feats = is_font(family, mods, at_size)
1166 if add_feats then get_features(add_feats, features) end
1167
1168 if type(source) == "string" then
1169 local cache = features.cache or "yes"
1170 if lua then
1171 if cache == "no" or cache == "rewrite" then
1172 loaded_font = create_font(source, lfs.type(source), lua, features.font, cache == "rewrite")
1173 else
1174 loaded_font = dofile(lua)
1175 end
1176 else
1177 lua = name_luafile(source, features.font)
1178 loaded_font = create_font(source, lfs.type(source), lua, features.font, cache ~= "no")
1179 end
1180 else
1181 if not done then
1182 if type(source) == "number" then
1183 wri.error("The library says `%s' matches `%s', but I can't find that file anywhere. Clean up your library!", original, lua)
1184 else
1185 recheck_fonts()
1186 return load_font(original, size, id, true)
1187 end
1188 else
1189 wri.error("I can't find `%s'. I return a default font to avoid further errors.", original)
1190 end
1191 end
1192
1193 if loaded_font then
1194
1195 local expansion = features.expansion and str.explode(features.expansion) or {}
1196 loaded_font.stretch = expansion[1] or 0
1197 loaded_font.shrink = expansion[2] or 0
1198 loaded_font.step = expansion[3] or 0
1199
1200 local extend = features.extend or 1
1201 loaded_font.extend = extend * 1000
1202 local slant
1203 if features.absoluteslant then
1204 local italic = loaded_font.italicangle or 0
1205 slant = features.absoluteslant - italic
1206 else
1207 slant = features.slant or 0
1208 end
1209 loaded_font.slant = num.tan(num.rad(slant)) * 1000
1210
1211 loaded_font = apply_size(loaded_font, size, features.letterspacing, features.space)
1212 loaded_font = activate_lookups(loaded_font, features, features.script, features.lang)
1213
1214 if #loaded_font == 0 then -- kludge for missing families/series, etc. 231207. jlrn.
1215 else -- kludge 231207
1216 loaded_font.name = loaded_font.name .. id
1217 loaded_font.fullname = loaded_font.fullname .. id
1218 local embedding = features.embedding or "subset"
1219 if embedding ~= "no" and embedding ~= "subset" and embedding ~= "full" then
1220 wri.error("Invalid value `%s' for the `embedding' feature. Value should be `no', `subset' or `full'.", embedding)
1221 embedding = "subset"
1222 end
1223 loaded_font.embedding = embedding
1224 end -- endkludge 231207
1225 else
1226 loaded_font = fl.read_tfm(lfs.find_file("cmr10", "tfm"), size)
1227 end
1228 end
1229 return loaded_font
1230 end
1231
1232 callback.register("define_font", load_font)
1233
1234 --[[
1235 History
1236 0.0.0 First release
1237 0.0.1 Bugfix
1238 0.0.2 2023-06-28 Bugfix on font path search: removed gsubs for Nix&Win
1239 0.0.3 2023-09-02 Bugfix on font path search: empty file extensions in font paths
1240 0.0.4 2023-12-07 Two kludges: one for missing ligatures, another for missing families/series;
1241 some cleanup and housekeeping.
1242 --]]