Debian Codegraph @

texmf-dist/tex/luatex/luaotfload/luaotfload-database.lua

raw
1 -----------------------------------------------------------------------
2 -- FILE: luaotfload-database.lua
3 -- DESCRIPTION: part of luaotfload / luaotfload-tool / font database
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-database",
8 version = "3.29", --TAGVERSION
9 date = "2024-12-03", --TAGDATE
10 description = "luaotfload submodule / database",
11 license = "GPL v2.0",
12 author = "Khaled Hosny, Elie Roux, Philipp Gesang, Marcel Krüger",
13 copyright = "Luaotfload Development Team",
14 }
15 end
16
17 --[[doc--
18
19 With version 2.7 we killed of the Fontforge libraries in favor of
20 the Lua implementation of the OT format reader. There were many
21 reasons to do this on top of the fact that FF won’t be around at
22 version 1.0 anymore: In addition to maintainability, memory safety
23 and general code hygiene, the new reader shows an amazing
24 performance: Scanning of the 3200 font files on my system takes
25 around 23 s now, as opposed to 74 s with the Fontforge libs. Memory
26 usage has improved drastically as well, as illustrated by these
27 profiles:
28
29 GB
30 1.324^ #
31 | #
32 | ::#
33 | : #::
34 | @: #:
35 | @: #:
36 | @@@: #:
37 | @@@ @: #:
38 | @@ @ @ @: #:
39 | @ @@:@ @ @: #: :
40 | @@ : @ :@ @ @: #: :
41 | @@: ::@@ :@@ ::@ :@ @ @: #: : :::
42 | @@ : :: @@ :@ : @ :@ @ @: #: : :: :
43 | @@ : ::: @@ :@ ::: @ :@ @ @: #: :: :: :
44 | @@@@ :: :::: @@ :@ : : @ :@ @ @: #: :: :::: ::
45 | :@ @@ :: :::: @@ :@ : :: : @ :@ @ @: #: :: :: :: ::
46 | @:@ @@ :: ::::: @@ :@ : :::: : @ :@ @ @: #: :::: :::: :: ::
47 | @@:@ @@ :: ::::::: @@ :@ : : :: : @ :@ @ @: #: ::: @: :: :: ::@
48 | @@@:@ @@ :: :: ::::: @@ :@ ::: :: : @ :@ @ @: #: ::: @: :: :: ::@
49 | @@@@@:@ @@ ::::::: ::::: @@ :@ ::: :: : @ :@ @ @: #: ::: ::@: :: :: ::@
50 0 +----------------------------------------------------------------------->GB
51 0 16.29
52
53 This is the memory usage during a complete database rebuild with
54 the Fontforge libraries. The same action using the new
55 ``getinfo()`` method gives a different picture:
56
57 MB
58 43.37^ #
59 | @ @ @#
60 | @@ @ @ @# :
61 | @@@ : @: @ @ @# :
62 | @ @@@ : : @: @ @: :@# :
63 | @ @ @@@ : : @: @ @: :@# :
64 | @ : : :@ @@@:::: @::@ @: :@#:: :
65 | :: : @ : @ : :::@ @ :@@@:::::@::@ @:::@#::::
66 | : @ : :: : :@:: :@: :::::@ @ :@@@:::::@::@:@:::@#::::
67 | :: :@ : @ ::@:@:::@:: :@: :::::@: :@ :@@@:::::@::@:@:::@#::::
68 | :: :@::: :@ ::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
69 | :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
70 | :::::@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
71 | ::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
72 | :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
73 | :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
74 | :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
75 | :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
76 | :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
77 | :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
78 0 +----------------------------------------------------------------------->GB
79 0 3.231
80
81 FF peaks at around 1.4 GB after 12.5 GB worth of allocations,
82 whereas the Lua implementation arrives at around 45 MB after 3.2 GB
83 total:
84
85 impl time(B) total(B) useful-heap(B) extra-heap(B)
86 fontforge 12,496,407,184 1,421,150,144 1,327,888,638 93,261,506
87 lua 3,263,698,960 45,478,640 37,231,892 8,246,748
88
89 Much of the inefficiency of Fontforge is a direct consequence of
90 having to parse the entire font to extract what essentially boils
91 down to a couple hundred bytes of metadata per font. Since some
92 information like design sizes (oh, Adobe!) is stuffed away in
93 Opentype tables, the vastly more efficient approach of
94 fontloader.info() proves insufficient for indexing. Thus, we ended
95 up using fontloader.open() which causes even the character tables
96 to be parsed, which incidentally are responsible for most of the
97 allocations during that peak of 1.4 GB measured above, along with
98 the encodings:
99
100 20.67% (293,781,048B) 0x6A8F72: SplineCharCreate (splineutil.c:3878)
101 09.82% (139,570,318B) 0x618ACD: _FontViewBaseCreate (fontviewbase.c:84)
102 08.77% (124,634,384B) 0x6A8FB3: SplineCharCreate (splineutil.c:3885)
103 04.53% (64,436,904B) in 80 places, all below massif's threshold (1.00%)
104 02.68% (38,071,520B) 0x64E14E: addKernPair (parsettfatt.c:493)
105 01.04% (14,735,320B) 0x64DE7D: addPairPos (parsettfatt.c:452)
106 39.26% (557,942,484B) 0x64A4E0: PsuedoEncodeUnencoded (parsettf.c:5706)
107
108 What gives? For 2.7 we expect a rougher transition than a year back
109 due to the complete revamp of the OT loading code. Breakage of
110 fragile aspects like font and style names has been anticipated and
111 addressed prior to the 2016 pretest release. In contrast to the
112 earlier approach of letting FF do a complete dump and then harvest
113 identifiers from the output we now have to coordinate with upstream
114 as to which fields are actually needed in order to provide a
115 similarly acceptable name → file lookup. On the bright side, these
116 things are a lot simpler to fix than the rather tedious work of
117 having users update their Luatex binary =)
118
119 --doc]]--
120
121 local lpeg = require "lpeg"
122 local P, lpegmatch = lpeg.P, lpeg.match
123
124 local log = luaotfload.log
125 local logreport = log and log.report or print -- overridden later on
126 local report_status = log.names_status
127 local report_status_start = log.names_status_start
128 local report_status_stop = log.names_status_stop
129
130
131 --- Luatex builtins
132 local load = load
133 local next = next
134 local require = require
135 local tonumber = tonumber
136 local unpack = table.unpack
137
138 local fonts = fonts or { }
139 do
140 local fontshandlers = fonts.handlers or { }
141 fonts.handlers = fontshandlers
142 end
143 local otfhandler = fonts.handlers.otf or { }
144
145 local gzipopen = gzip.open
146 local iolines = io.lines
147 local ioopen = io.open
148 local kpseexpand_path = kpse.expand_path
149 local kpsefind_file = kpse.find_file
150 local kpselookup = kpse.lookup
151 local kpsereadable_file = kpse.readable_file
152 local lfsattributes = lfs.attributes
153 local lfscurrentdir = lfs.currentdir
154 local lfsdir = lfs.dir
155 local mathabs = math.abs
156 local mathmin = math.min
157 local osgetenv = os.getenv
158 local osgettimeofday = os.gettimeofday
159 local osremove = os.remove
160 local dump = string.dump
161 local stringfind = string.find
162 local stringformat = string.format
163 local stringgmatch = string.gmatch
164 local stringgsub = string.gsub
165 local stringlower = string.lower
166 local stringsub = string.sub
167 local tableconcat = table.concat
168 local tablesort = table.sort
169 local utf8len = utf8.len
170 local utf8offset = utf8.offset
171
172 --- these come from Lualibs/Context
173 local context_environment = luaotfload.fontloader
174 local caches = context_environment.caches
175 local filebasename = file.basename
176 local filedirname = file.dirname
177 local fileextname = file.extname
178 local fileiswritable = file.iswritable
179 local filejoin = file.join
180 local filenameonly = file.nameonly
181 local filereplacesuffix = file.replacesuffix
182 local filesplitpath = file.splitpath or file.split_path
183 local filesuffix = file.suffix
184 local getwritablepath = caches.getwritablepath
185 local lfsisdir = lfs.isdir
186 local lfsisfile = lfs.isfile
187 local lfsmkdirs = lfs.mkdirs
188 local lpegsplitat = lpeg.splitat
189 local stringis_empty = string.is_empty
190 local stringsplit = string.split
191 local stringstrip = string.strip
192 local tableappend = table.append
193 local tablecontains = table.contains
194 local tablecopy = table.copy
195 local tablefastcopy = table.fastcopy
196 local tabletofile = table.tofile
197 local tableserialize = table.serialize
198 local names = fonts and fonts.names or { }
199 local resolversfindfile = context_environment.resolvers.findfile
200
201 --- some of our own
202 local unicode = require'luaotfload-unicode'
203 local casefold = require'lua-uni-case'.casefold
204 local realpath = require'luaotfload-realpath'.realpath
205 local alphnum_only = unicode.alphnum_only
206
207 local name_index = nil --> upvalue for names.data
208 local lookup_cache = nil --> for names.lookups
209
210 --- string -> (string * string)
211 local function make_luanames (path)
212 return filereplacesuffix(path, "lua"),
213 filereplacesuffix(path, "luc")
214 end
215
216 local format_precedence = {
217 "otf", "ttc", "ttf", "afm", "pfb"
218 }
219
220 local location_precedence = {
221 "local", "system", "texmf",
222 }
223 local enabled_locations = {
224 ['local'] = true,
225 system = true,
226 texmf = true,
227 }
228
229 local function set_location_precedence (precedence)
230 location_precedence = precedence
231 for location in next, enabled_locations do
232 enabled_locations[location] = nil
233 end
234 for _, location in ipairs(location_precedence) do
235 enabled_locations[location] = location ~= 'local' or config.luaotfload.db.scan_local == true
236 end
237 end
238
239 --[[doc--
240
241 Auxiliary functions
242
243 --doc]]--
244
245 --- fontnames contain all kinds of garbage; as a precaution we
246 --- lowercase and strip them of non alphanumerical characters
247
248 --- string -> string
249
250 local macroman2utf8 do
251 local mapping = {
252 [0x80] = 0x00C4, [0x81] = 0x00C5, [0x82] = 0x00C7, [0x83] = 0x00C9,
253 [0x84] = 0x00D1, [0x85] = 0x00D6, [0x86] = 0x00DC, [0x87] = 0x00E1,
254 [0x88] = 0x00E0, [0x89] = 0x00E2, [0x8A] = 0x00E4, [0x8B] = 0x00E3,
255 [0x8C] = 0x00E5, [0x8D] = 0x00E7, [0x8E] = 0x00E9, [0x8F] = 0x00E8,
256 [0x90] = 0x00EA, [0x91] = 0x00EB, [0x92] = 0x00ED, [0x93] = 0x00EC,
257 [0x94] = 0x00EE, [0x95] = 0x00EF, [0x96] = 0x00F1, [0x97] = 0x00F3,
258 [0x98] = 0x00F2, [0x99] = 0x00F4, [0x9A] = 0x00F6, [0x9B] = 0x00F5,
259 [0x9C] = 0x00FA, [0x9D] = 0x00F9, [0x9E] = 0x00FB, [0x9F] = 0x00FC,
260 [0xA0] = 0x2020, [0xA1] = 0x00B0, [0xA2] = 0x00A2, [0xA3] = 0x00A3,
261 [0xA4] = 0x00A7, [0xA5] = 0x2022, [0xA6] = 0x00B6, [0xA7] = 0x00DF,
262 [0xA8] = 0x00AE, [0xA9] = 0x00A9, [0xAA] = 0x2122, [0xAB] = 0x00B4,
263 [0xAC] = 0x00A8, [0xAD] = 0x2260, [0xAE] = 0x00C6, [0xAF] = 0x00D8,
264 [0xB0] = 0x221E, [0xB1] = 0x00B1, [0xB2] = 0x2264, [0xB3] = 0x2265,
265 [0xB4] = 0x00A5, [0xB5] = 0x00B5, [0xB6] = 0x2202, [0xB7] = 0x2211,
266 [0xB8] = 0x220F, [0xB9] = 0x03C0, [0xBA] = 0x222B, [0xBB] = 0x00AA,
267 [0xBC] = 0x00BA, [0xBD] = 0x03A9, [0xBE] = 0x00E6, [0xBF] = 0x00F8,
268 [0xC0] = 0x00BF, [0xC1] = 0x00A1, [0xC2] = 0x00AC, [0xC3] = 0x221A,
269 [0xC4] = 0x0192, [0xC5] = 0x2248, [0xC6] = 0x2206, [0xC7] = 0x00AB,
270 [0xC8] = 0x00BB, [0xC9] = 0x2026, [0xCA] = 0x00A0, [0xCB] = 0x00C0,
271 [0xCC] = 0x00C3, [0xCD] = 0x00D5, [0xCE] = 0x0152, [0xCF] = 0x0153,
272 [0xD0] = 0x2013, [0xD1] = 0x2014, [0xD2] = 0x201C, [0xD3] = 0x201D,
273 [0xD4] = 0x2018, [0xD5] = 0x2019, [0xD6] = 0x00F7, [0xD7] = 0x25CA,
274 [0xD8] = 0x00FF, [0xD9] = 0x0178, [0xDA] = 0x2044, [0xDB] = 0x20AC,
275 [0xDC] = 0x2039, [0xDD] = 0x203A, [0xDE] = 0xFB01, [0xDF] = 0xFB02,
276 [0xE0] = 0x2021, [0xE1] = 0x00B7, [0xE2] = 0x201A, [0xE3] = 0x201E,
277 [0xE4] = 0x2030, [0xE5] = 0x00C2, [0xE6] = 0x00CA, [0xE7] = 0x00C1,
278 [0xE8] = 0x00CB, [0xE9] = 0x00C8, [0xEA] = 0x00CD, [0xEB] = 0x00CE,
279 [0xEC] = 0x00CF, [0xED] = 0x00CC, [0xEE] = 0x00D3, [0xEF] = 0x00D4,
280 [0xF0] = 0xF8FF, [0xF1] = 0x00D2, [0xF2] = 0x00DA, [0xF3] = 0x00DB,
281 [0xF4] = 0x00D9, [0xF5] = 0x0131, [0xF6] = 0x02C6, [0xF7] = 0x02DC,
282 [0xF8] = 0x00AF, [0xF9] = 0x02D8, [0xFA] = 0x02D9, [0xFB] = 0x02DA,
283 [0xFC] = 0x00B8, [0xFD] = 0x02DD, [0xFE] = 0x02DB, [0xFF] = 0x02C7,
284 }
285 function macroman2utf8(s)
286 local bytes = {string.byte(s, 1, -1)}
287 for i=1,#bytes do
288 bytes[i] = mapping[bytes[i]] or bytes[i]
289 end
290 return utf8.char(table.unpack(bytes))
291 end
292 end
293 local function sanitize_fontname (str)
294 if str ~= nil then
295 str = utf8len(str) and str or macroman2utf8(str)
296 str = alphnum_only(casefold(str, true))
297 return str
298 end
299 return nil
300 end
301
302 local function sanitize_fontnames (rawnames)
303 local result = { }
304 for category, namedata in next, rawnames do
305
306 if type (namedata) == "string" then
307 namedata = utf8len(namedata) and namedata or macroman2utf8(namedata)
308 result [category] = alphnum_only(casefold(namedata, true))
309 else
310 local target = { }
311 for field, name in next, namedata do
312 name = utf8len(name) and name or macroman2utf8(name)
313 target [field] = alphnum_only(casefold(name, true))
314 end
315 result [category] = target
316 end
317 end
318 return result
319 end
320
321 local list_dir_or_empty do
322 local function inner_list_dir_or_empty (dir, success, ...)
323 if success then
324 return ...
325 else
326 -- Skipping unreadable directory.
327 -- TODO: Print warning
328 return next, {}
329 end
330 end
331 function list_dir_or_empty (dir)
332 return inner_list_dir_or_empty(dir, pcall(lfsdir, dir))
333 end
334 end
335
336 local function dummyfilter () return true end
337
338 --- the optional filter function receives the full path of a file
339 --- system entity. a filter applies if the first argument it returns is
340 --- true.
341
342 --- string -> function? -> string list
343 local function find_files (root, filter)
344 if not lfsisdir (root) then return end
345
346 local files = {}
347 local dirs = { root }
348 filter = filter or dummyfilter
349
350 while dirs[1] do
351 local dir = dirs[#dirs]
352 dirs[#dirs] = nil
353
354 for ent in list_dir_or_empty (dir) do
355 if ent ~= "." and ent ~= ".." then
356 local fullpath = dir .. "/" .. ent
357 if filter (fullpath) == true then
358 if lfsisdir (fullpath) then
359 dirs[#dirs+1] = fullpath
360 elseif lfsisfile (fullpath) then
361 files[#files+1] = fullpath
362 end
363 end
364 end
365 end
366 end
367 return files
368 end
369
370
371 --[[doc--
372 This is a sketch of the luaotfload db:
373
374 type dbobj = {
375 families : familytable;
376 fontnames : fontnametable;
377 files : filemap;
378 status : filestatus;
379 mappings : fontentry list;
380 meta : metadata;
381 }
382 and familytable = {
383 local : (format, familyentry) hash; // specified with include dir
384 texmf : (format, familyentry) hash;
385 system : (format, familyentry) hash;
386 }
387 and familyentry = {
388 r : sizes; // regular
389 i : sizes; // italic
390 b : sizes; // bold
391 bi : sizes; // bold italic
392 }
393 and sizes = {
394 default : int; // points into mappings or names
395 optical : (int, int) list; // design size -> index entry
396 }
397 and fontnametable = {
398 local : (format, index) hash;
399 texmf : (format, index) hash;
400 system : (format, index) hash;
401 }
402 and metadata = {
403 created : string // creation time
404 formats : string list; // { "otf", "ttf", "ttc" }
405 local : bool; (* set if local fonts were added to the db *)
406 modified : string // modification time
407 statistics : TODO; // created when built with "--stats"
408 version : float; // index version
409 }
410 and filemap = { // created by generate_filedata()
411 base : {
412 local : (string, int) hash; // basename -> idx
413 system : (string, int) hash;
414 texmf : (string, int) hash;
415 };
416 bare : {
417 local : (string, (string, int) hash) hash; // location -> (barename -> idx)
418 system : (string, (string, int) hash) hash;
419 texmf : (string, (string, int) hash) hash;
420 };
421 full : (int, string) hash; // idx -> full path
422 }
423 and fontentry = { // finalized by collect_families()
424 basename : string; // file name without path "foo.otf"
425 conflicts : { barename : int; basename : int }; // filename conflict with font at index; happens with subfonts
426 familyname : string; // sanitized name of the font family the font belongs to, usually from the names table
427 fontname : string; // sanitized name of the font
428 format : string; // "otf" | "ttf" | "afm" (* | "pfb" *)
429 fullname : string; // sanitized full name of the font including style modifiers
430 fullpath : string; // path to font in filesystem
431 index : int; // index in the mappings table
432 italicangle : float; // italic angle; non-zero with oblique faces
433 location : string; // "texmf" | "system" | "local"
434 plainname : string; // unsanitized font name
435 typographicsubfamily : string; // sanitized preferred subfamily (names table 14)
436 psname : string; // PostScript name
437 size : (false | float * float * float); // if available, size info from the size table converted from decipoints
438 subfamily : string; // sanitized subfamily (names table 2)
439 subfont : (int | bool); // integer if font is part of a TrueType collection ("ttc")
440 version : string; // font version string
441 weight : int; // usWeightClass
442 }
443 and filestatus = (string, // fullname
444 { index : int list; // pointer into mappings
445 timestamp : int; }) dict
446
447 beware that this is a reconstruction and may be incomplete or out of
448 date. Last update: 2014-04-06, describing version 2.51.
449
450 mtx-fonts has in names.tma:
451
452 type names = {
453 cache_uuid : uuid;
454 cache_version : float;
455 datastate : uuid list;
456 fallbacks : (filetype, (basename, int) hash) hash;
457 families : (basename, int list) hash;
458 files : (filename, fullname) hash;
459 indices : (fullname, int) hash;
460 mappings : (filetype, (basename, int) hash) hash;
461 names : ? (empty hash) ?;
462 rejected : (basename, int) hash;
463 specifications: fontentry list;
464 }
465 and fontentry = {
466 designsize : int;
467 familyname : string;
468 filename : string;
469 fontname : string;
470 format : string;
471 fullname : string;
472 maxsize : int;
473 minsize : int;
474 modification : int;
475 rawname : string;
476 style : string;
477 subfamily : string;
478 variant : string;
479 weight : string;
480 width : string;
481 }
482
483 --doc]]--
484
485 --- string list -> string option -> dbobj
486
487 local function initialize_namedata (formats, created)
488 local now = os.date "%Y-%m-%d %H:%M:%S" --- i. e. "%F %T" on POSIX systems
489 return {
490 status = { }, -- was: status; map abspath -> mapping
491 mappings = { }, -- TODO: check if still necessary after rewrite
492 files = { }, -- created later
493 meta = {
494 created = created or now,
495 formats = formats,
496 ["local"] = false,
497 modified = now,
498 statistics = { },
499 version = names.version,
500 },
501 }
502 end
503
504 -- A helper to load a file which might be gziped
505 local function load_maybe_gzip (path, binary)
506 local gzippath = path .. '.gz'
507 local f = ioopen (gzippath, 'rb')
508 if f then
509 path = gzippath
510 local result = f:read'*a'
511 result = gzip.decompress(result, 31)
512 f:close()
513 return path, result
514 else
515 f, msg = ioopen (path, binary and 'rb' or 'r')
516 if f then
517 local result = f:read'*a'
518 f:close()
519 return path, result
520 end
521 end
522
523 return nil, msg
524 end
525
526 --- When loading a lua file we try its binary complement first, which
527 --- is assumed to be located at an identical path, carrying the suffix
528 --- .luc.
529
530 --- string -> string -> (string * table)
531 local function load_lua_file (path_lua, path_luc)
532 local foundname, chunk = load_maybe_gzip (path_luc, true)
533 if foundname then
534 chunk = load (chunk, 'b')
535 else
536 chunk = nil
537 end
538 if not chunk then
539 foundname, chunk = load_maybe_gzip (path_lua, false)
540 if foundname then
541 chunk = assert (load (chunk, 't'))
542 else
543 return nil
544 end
545 end
546
547 return foundname, chunk()
548 end
549
550 --- define locals in scope
551 local get_font_filter
552 local lookup_font_name
553 local reload_db
554 local lookup_fullpath
555 local save_lookups
556 local save_names
557 local set_font_filter
558 local update_names
559
560 --- state of the database
561 local fonts_reloaded = false
562
563 --- limit output when approximate font matching (luaotfload-tool -F)
564 local fuzzy_limit = 1 --- display closest only
565
566 --- bool? -> -> bool? -> dbobj option
567 local function load_names (dry_run, no_rebuild)
568 local starttime = osgettimeofday ()
569 local foundname, data = load_lua_file (config.luaotfload.paths.index_path_lua,
570 config.luaotfload.paths.index_path_luc)
571
572 if data then
573 logreport ("log", 0, "db",
574 "Font names database loaded from %s", foundname)
575 logreport ("term", 3, "db",
576 "Font names database loaded from %s", foundname)
577 logreport ("info", 3, "db", "Loading took %0.f ms.",
578 1000 * (osgettimeofday () - starttime))
579
580 local db_version, names_version
581 if data.meta then
582 db_version = data.meta.version
583 else
584 --- Compatibility branch; the version info used to be
585 --- stored in the table root which is why updating from
586 --- an earlier index version broke.
587 db_version = data.version or -42 --- invalid
588 end
589 names_version = names.version
590 if db_version ~= names_version then
591 if math.tointeger(db_version) then
592 logreport ("both", 0, "db",
593 [[Version mismatch; expected %d, got %d.]],
594 names_version, db_version)
595 else
596 logreport ("both", 0, "db",
597 [[Version mismatch; expected %d, got invalid data.]],
598 names_version, db_version)
599 end
600 if not fonts_reloaded then
601 logreport ("both", 0, "db", [[Force rebuild.]])
602 data = update_names (initialize_namedata (get_font_filter ()),
603 true, false)
604 if not data then
605 logreport ("both", 0, "db",
606 "Database creation unsuccessful.")
607 end
608 end
609 end
610 else
611 if no_rebuild == true then
612 logreport ("both", 2, "db",
613 [[Database does not exist, skipping rebuild though.]])
614 return false
615 end
616 logreport ("both", 0, "db",
617 [[Font names database not found, generating new one.]])
618 logreport ("both", 0, "db",
619 [[This can take several minutes; please be patient.]])
620 data = update_names (initialize_namedata (get_font_filter ()),
621 nil, dry_run)
622 if not data then
623 logreport ("both", 0, "db", "Database creation unsuccessful.")
624 end
625 end
626 return data
627 end
628
629 --[[doc--
630
631 access_font_index -- Provide a reference of the index table. Will
632 cause the index to be loaded if not present.
633
634 --doc]]--
635
636 local function access_font_index ()
637 if not name_index then name_index = load_names () end
638 return name_index
639 end
640
641 local function getmetadata ()
642 if not name_index then
643 name_index = load_names (false, true)
644 if name_index then return tablefastcopy (name_index.meta) end
645 end
646 return false
647 end
648
649 --- unit -> unit
650 local function load_lookups ( )
651 local foundname, data = load_lua_file(config.luaotfload.paths.lookup_path_lua,
652 config.luaotfload.paths.lookup_path_luc)
653 if data then
654 logreport ("log", 0, "cache", "Lookup cache loaded from %s.", foundname)
655 logreport ("term", 3, "cache",
656 "Lookup cache loaded from %s.", foundname)
657 else
658 logreport ("both", 1, "cache",
659 "No lookup cache, creating empty.")
660 data = { }
661 end
662 lookup_cache = data
663 end
664
665 local regular_synonym = {
666 book = 0,
667 normal = 0,
668 plain = 0,
669 regular = 0,
670 roman = 0,
671 medium = 1000, -- Some font authors haven't got the memo that medium is not regular
672 }
673
674 local style_synonym = {
675 oblique = 'i',
676 slanted = 'i',
677 italic = 'i',
678 boldoblique = 'bi',
679 boldslanted = 'bi',
680 bolditalic = 'bi',
681 bold = 'b',
682 }
683
684 -- MK Determine if casefold search is requested
685 local casefold_search =
686 not ({['0'] = true, ['f'] = true, [''] = true})
687 [(kpse.var_value'texmf_casefold_search' or '1'):sub(1,1)]
688 -- /MK
689
690 local function lookup_filename (filename)
691 if not name_index then name_index = load_names () end
692 local files = name_index.files
693 local basedata = files.base
694 local baredata = files.bare
695 for i = 1, #location_precedence do
696 local location = location_precedence [i]
697 local basenames = basedata [location]
698 local barenames = baredata [location]
699 local idx
700 if basenames ~= nil then
701 -- MK Added fallback
702 idx = basenames [filename]
703 or casefold_search and basenames [stringlower(filename)]
704 -- /MK
705 if idx then
706 goto done
707 end
708 end
709 if barenames ~= nil then
710 for j = 1, #format_precedence do
711 local format = format_precedence [j]
712 local filemap = barenames [format]
713 if filemap then
714 -- MK Added fallback
715 idx = barenames [format] [filename]
716 or casefold_search and barenames [format] [stringlower(filename)]
717 -- /MK
718 if idx then
719 break
720 end
721 end
722 end
723 end
724 ::done::
725 if idx then
726 return files.full [idx]
727 end
728 end
729 end
730
731 --[[doc--
732
733 lookup_font_file -- The ``file:`` are ultimately delegated here.
734 The lookups are kind of a blunt instrument since they try locating
735 the file using every conceivable method, which is quite
736 inefficient. Nevertheless, resolving files that way is rarely the
737 bottleneck.
738
739 --doc]]--
740
741 --- string -> string * string * bool
742 local lookup_font_file
743
744 -- MK Added mini scope to avoid variable limit
745 do
746 local type1_metrics = { "tfm", "ofm", }
747 -- /MK
748
749 function lookup_font_file (filename)
750 local found = lookup_filename (filename)
751
752 if found and not lfsisfile(found) then
753 found = nil
754 end
755
756 if not found then
757 local type = file.suffix(filename)
758 if type ~= "" then
759 found = resolversfindfile(filename, type)
760 end
761 end
762
763 if found then
764 return found, nil, true
765 end
766
767 for i=1, #type1_metrics do
768 local format = type1_metrics[i]
769 if resolversfindfile(filename, format) then
770 return file.addsuffix(filename, format), format, true
771 end
772 end
773
774 if not fonts_reloaded and config.luaotfload.db.update_live == true then
775 return reload_db (stringformat ("File not found: %q.", filename),
776 lookup_font_file,
777 filename)
778 end
779 return filename, nil, false
780 end
781 -- MK
782 end
783 -- /MK
784
785 --[[doc--
786
787 get_font_file -- Look up the file of an entry in the mappings
788 table. If the index is valid, pass on the name and subfont index
789 after verifying the existence of the resolved file. This
790 verification differs depending the index entry’s ``location``
791 field:
792
793 * ``texmf`` fonts are verified using the (slow) function
794 ``kpse.lookup()``;
795 * other locations are tested by resolving the full path and
796 checking for the presence of a file there.
797
798 --doc]]--
799
800 --- int -> bool * (string * int) option
801 local function get_font_file (index)
802 local entry = name_index.mappings [index]
803 if not entry then
804 return false
805 end
806 local basename = entry.basename
807 if entry.location == "texmf" then
808 local fullname = resolversfindfile(basename, entry.format)
809 if fullname then
810 return true, fullname, entry.subfont
811 end
812 else --- system, local
813 local fullname = name_index.files.full [index]
814 if lfsisfile (fullname) then
815 return true, fullname, entry.subfont
816 end
817 end
818 return false
819 end
820
821 --[[doc--
822 We need to verify if the result of a cached lookup actually exists in
823 the texmf or filesystem. Again, due to the schizoprenic nature of the
824 font management we have to check both the system path and the texmf.
825 --doc]]--
826
827 local function verify_font_file (basename)
828 local path = lookup_fullpath (basename)
829 if path and lfsisfile(path) then
830 return true
831 end
832 if resolversfindfile(basename) then
833 return true
834 end
835 return false
836 end
837
838 --[[doc--
839 Lookups can be quite costly, more so the less specific they are.
840 Even if we find a matching font eventually, the next time the
841 user compiles Eir document E will have to stand through the delay
842 again.
843 Thus, some caching of results -- even between runs -- is in order.
844 We’ll just store successful name: lookups in a separate cache file.
845
846 type lookup_cache = (string, (string * num)) dict
847
848 The spec is expected to be modified in place (ugh), so we’ll have to
849 catalogue what fields actually influence its behavior.
850
851 Idk what the “spec” resolver is for.
852
853 lookup inspects modifies
854 ---------- ----------------- ---------------------------
855 file: name forced, name
856 name:[*] name, style, sub, resolved, sub, name, forced
857 optsize, size
858 spec: name, sub resolved, sub, name, forced
859
860 [*] name: contains both the name resolver from luatex-fonts and
861 lookup_font_name () below
862
863 From my reading of font-def.lua, what a resolver does is
864 basically rewrite the “name” field of the specification record
865 with the resolution.
866 Also, the fields “resolved”, “sub”, “force” etc. influence the outcome.
867
868 --doc]]--
869
870 local hash_request do
871 local concat_char = "#"
872 local hash_fields = {
873 --- order is important
874 "specification", "style", "sub", "optsize", "size",
875 }
876 local n_hash_fields = #hash_fields
877
878 --- spec -> string
879 function hash_request (specification)
880 local key = { } --- segments of the hash
881 for i=1, n_hash_fields do
882 local field = specification[hash_fields[i]]
883 if field then
884 key[#key+1] = field
885 end
886 end
887 return tableconcat(key, concat_char)
888 end
889 end
890
891 --- 'a -> 'a -> table -> (string * int|boolean * boolean)
892 local function lookup_font_name_cached (specification)
893 if not lookup_cache then load_lookups () end
894 local request = hash_request(specification)
895 logreport ("both", 4, "cache", "Looking for %q in cache ...",
896 request)
897
898 local found = lookup_cache [request]
899
900 --- case 1) cache positive ----------------------------------------
901 if found then --- replay fields from cache hit
902 logreport ("info", 4, "cache", "Found!")
903 local basename = found[1]
904 --- check the presence of the file in case it’s been removed
905 local success = verify_font_file (basename)
906 if success == true then
907 return basename, found[2], true
908 end
909 logreport ("both", 4, "cache",
910 "Cached file not found; resolving again.")
911 else
912 logreport ("both", 4, "cache", "Not cached; resolving.")
913 end
914
915 --- case 2) cache negative ----------------------------------------
916 --- first we resolve normally ...
917 local filename, subfont = lookup_font_name (specification)
918 if not filename then
919 return nil, nil
920 end
921 --- ... then we add the fields to the cache ... ...
922 local entry = { filename, subfont }
923 logreport ("both", 4, "cache", "New entry: %s.", request)
924 lookup_cache [request] = entry
925
926 --- obviously, the updated cache needs to be stored.
927 --- TODO this should trigger a save only once the
928 --- document is compiled (finish_pdffile callback?)
929 logreport ("both", 5, "cache", "Saving updated cache.")
930 local success = save_lookups ()
931 if not success then --- sad, but not critical
932 logreport ("both", 0, "cache", "Error writing cache.")
933 end
934 return filename, subfont
935 end
936
937 --- this used to be inlined; with the lookup cache we don’t
938 --- have to be parsimonious wrt function calls anymore
939 --- “found” is the match accumulator
940 local function add_to_match (found, size, face)
941
942 local continue = true
943
944 local optsize = face.size
945
946 if optsize and next (optsize) then
947 local dsnsize, maxsize, minsize
948 dsnsize = optsize[1]
949 maxsize = optsize[2]
950 minsize = optsize[3]
951
952 if size ~= nil
953 and (dsnsize == size or (size > minsize and size <= maxsize))
954 then
955 found[1] = face
956 continue = false ---> break
957 else
958 found[#found+1] = face
959 end
960 else
961 found[1] = face
962 continue = false ---> break
963 end
964
965 return found, continue
966 end
967
968 local function choose_closest (distances)
969 local closest = 2^51
970 local match
971 for i = 1, #distances do
972 local d, index = unpack (distances [i])
973 if d < closest then
974 closest = d
975 match = index
976 end
977 end
978 return match
979 end
980
981 --[[doc--
982
983 choose_size -- Pick a font face of appropriate size (in sp) from
984 the list of family members with matching style. There are three
985 categories:
986
987 1. exact matches: if there is a face whose design size equals
988 the asked size, it is returned immediately and no further
989 candidates are inspected.
990
991 2. range matches: of all faces in whose design range the
992 requested size falls the one whose center the requested
993 size is closest to is returned.
994
995 3. out-of-range matches: of all other faces (i. e. whose range
996 is above or below the asked size) the one is chosen whose
997 boundary (upper or lower) is closest to the requested size.
998
999 4. default matches: if no design size or a design size of zero
1000 is requested, the face with the default size is returned.
1001
1002 --doc]]--
1003
1004 --- int * int * int * int list -> int -> int
1005 local function choose_size (sizes, askedsize)
1006 local inrange = { } --- distance * index list
1007 local norange = { } --- distance * index list
1008 if askedsize ~= 0 then
1009 --- firstly, look for an exactly matching design size or
1010 --- matching range
1011 for i = 1, #sizes do
1012 local dsnsize, high, low, index = unpack (sizes [i])
1013 if dsnsize == askedsize then
1014 --- exact match, this is what we were looking for
1015 return index
1016 elseif askedsize <= low then
1017 --- below range, add to the norange table
1018 local d = low - askedsize
1019 norange [#norange + 1] = { d, index }
1020 elseif askedsize > high then
1021 --- beyond range, add to the norange table
1022 local d = askedsize - high
1023 norange [#norange + 1] = { d, index }
1024 else
1025 --- range match
1026 local d = 0
1027
1028 -- should always be true. Just in case there's some
1029 -- weried fonts out there
1030 if dsnsize > low and dsnsize < high then
1031 d = dsnsize - askedsize
1032 else
1033 d = ((low + high) / 2) - askedsize
1034 end
1035 if d < 0 then
1036 d = -d
1037 end
1038
1039 inrange [#inrange + 1] = { d, index }
1040 end
1041 end
1042 end
1043 ::skip::
1044 if #inrange > 0 then
1045 return choose_closest (inrange)
1046 elseif #norange > 0 then
1047 return choose_closest (norange)
1048 elseif sizes.default then
1049 return sizes.default
1050 elseif askedsize == 0 then
1051 return choose_size(sizes, 655360) -- If there is no default size and no size specified, just guess
1052 end
1053 end
1054
1055 --[[doc--
1056
1057 lookup_familyname -- Query the families table for an entry
1058 matching the specification.
1059 The parameters “name” and “style” are pre-sanitized.
1060
1061 --doc]]--
1062 --- spec -> string -> string -> int -> string * int * bool
1063 local function lookup_familyname (specification, name, style, askedsize)
1064 local families = name_index.families
1065 local candidates = nil
1066 local fallback = true
1067 --- arrow code alert
1068 for i = 1, #location_precedence do
1069 local location = location_precedence [i]
1070 local locgroup = families [location]
1071 for j = 1, #format_precedence do
1072 local format = format_precedence [j]
1073 local fmtgroup = locgroup [format]
1074 if fmtgroup then
1075 local familygroup = fmtgroup [name]
1076 if familygroup then
1077 local stylegroup = familygroup [style]
1078 if stylegroup then --- suitable match
1079 candidates = stylegroup
1080 fallback = false
1081 goto done
1082 elseif not candidates then
1083 candidates = familygroup.r
1084 end
1085 end
1086 end
1087 end
1088 end
1089 if not candidates then
1090 return nil, nil
1091 end
1092 ::done::
1093 index = choose_size (candidates, askedsize)
1094 local success, resolved, subfont = get_font_file (index)
1095 if not success then
1096 return nil, nil
1097 end
1098 logreport ("info", 2, "db", "Match found: %s(%d).",
1099 resolved, subfont or 0)
1100 return resolved, subfont, fallback
1101 end
1102
1103 local function lookup_fontname (specification, name)
1104 local fontnames = name_index.fontnames
1105 --- arrow code alert
1106 for i = 1, #location_precedence do
1107 local location = location_precedence [i]
1108 local locgroup = fontnames [location]
1109 for j = 1, #format_precedence do
1110 local format = format_precedence [j]
1111 local fmtgroup = locgroup [format]
1112 if fmtgroup then
1113 local index = fmtgroup [name]
1114 if index then
1115 local success, resolved, subfont = get_font_file (index)
1116 if success then
1117 return resolved, subfont
1118 end
1119 end
1120 end
1121 end
1122 end
1123 end
1124
1125 local design_size_dimension --- scale asked size if not using bp
1126 local set_size_dimension --- called from config
1127 do
1128
1129 --- cf. TeXbook p. 57; the index stores sizes pre-scaled from bp to
1130 --- sp. This allows requesting sizes we got from the TeX end
1131 --- without further conversion. For the other options *pt* and *dd*
1132 --- we scale the requested size as though the value in the font was
1133 --- specified in the requested unit.
1134
1135 --- From @zhouyan:
1136
1137 --- Let P be the asked size in pt, and Aᵤ = CᵤP, where u is the
1138 --- designed unit, pt, bp, or dd, and
1139 ---
1140 --- Cpt = 1, Cbp = 7200/7227, Cdd = 1157/1238.
1141 ---
1142 --- That is, Aᵤ is the asked size in the desired unit. Let D be the
1143 --- de-sign size (assumed to be in the unit of bp) as reported by
1144 --- the font (divided by 10; in all the following we ignore the
1145 --- factor 2^16 ).
1146 ---
1147 --- For simplicity, consider only the case of exact match to the
1148 --- design size. That is, we would like to have Aᵤ = D. Let A′ᵤ = αᵤP
1149 --- and D′ = βD be the scaled values used in comparisons. For the
1150 --- comparison to work correctly, we need,
1151 ---
1152 --- Aᵤ = D ⟺ A′ᵤ = D′ ,
1153 ---
1154 --- and thus αᵤ = βCᵤ. The fix in PR 400 is the case of β = 1. The
1155 --- fix for review is β = 7227/7200, and the value of αᵤ is thus
1156 --- correct for pt, bp, but not for dd.
1157
1158 local dimens = {
1159 bp = false,
1160 pt = 7227 / 7200,
1161 dd = (7227 / 7200) * (1157 / 1238),
1162 }
1163
1164 design_size_dimension = dimens.bp
1165
1166 function set_size_dimension (dim)
1167 local conv = dimens [dim]
1168 if conv ~= nil then
1169 logreport ("both", 4, "db",
1170 "Interpreting design sizes as %q, factor %.6f.",
1171 dim, conv or 1)
1172 design_size_dimension = conv
1173 return
1174 end
1175 logreport ("both", 0, "db",
1176 "Invalid dimension %q requested for design sizes; \z
1177 ignoring.")
1178 end
1179 end
1180
1181
1182 --[[doc--
1183
1184 lookup_font_name -- Perform a name: lookup. This first queries the
1185 font families table and, if there is no match for the spec, the
1186 font names table.
1187 The return value is a pair consisting of the file name and the
1188 subfont index if appropriate..
1189
1190 the request specification has the fields:
1191
1192 · features: table
1193 · normal: set of { ccmp clig itlc kern liga locl mark mkmk rlig }
1194 · ???
1195 · forced: string
1196 · lookup: "name"
1197 · method: string
1198 · name: string
1199 · resolved: string
1200 · size: int
1201 · specification: string (== <lookup> ":" <name>)
1202 · sub: string
1203
1204 The “size” field deserves special attention: if its value is
1205 negative, then it actually specifies a scalefactor of the
1206 design size of the requested font. This happens e.g. if a font is
1207 requested without an explicit “at size”. If the font is part of a
1208 larger collection with different design sizes, this complicates
1209 matters a bit: Normally, the resolver prefers fonts that have a
1210 design size as close as possible to the requested size. If no
1211 size specified, then the design size is implied. But which design
1212 size should that be? Xetex appears to pick the “normal” (unmarked)
1213 size: with Adobe fonts this would be the one that is neither
1214 “caption” nor “subhead” nor “display” &c ... For fonts by Adobe this
1215 seems to be the one that does not receive a “typographicsubfamily”
1216 field. (IOW Adobe uses the “typographicsubfamily” field to encode
1217 the design size in more or less human readable format.) However,
1218 this is not true of LM and EB Garamond. As this matters only where
1219 there are multiple design sizes to a given font/style combination,
1220 we put a workaround in place that chooses that unmarked version.
1221
1222 The first return value of “lookup_font_name” is the file name of the
1223 requested font (string). It can be passed to the fullname resolver
1224 get_font_file().
1225 The second value is either “false” or an integer indicating the
1226 subfont index in a TTC.
1227
1228 --doc]]--
1229
1230 --- table -> string * (int | bool)
1231 function lookup_font_name (specification)
1232 if not name_index then name_index = load_names () end
1233 local name = sanitize_fontname (specification.name)
1234 local style = sanitize_fontname (specification.style) or "r"
1235 local askedsize = specification.optsize
1236
1237 if askedsize then
1238 askedsize = tonumber (askedsize) * 65536
1239 else
1240 askedsize = specification.size
1241 if not askedsize or askedsize < 0 then
1242 askedsize = 0
1243 end
1244 end
1245
1246 if design_size_dimension ~= false then
1247 askedsize = design_size_dimension * askedsize
1248 end
1249
1250 local resolved, subfont, fallback = lookup_familyname (specification,
1251 name,
1252 style,
1253 askedsize)
1254 if not resolved or fallback then
1255 local new_resolved, new_subfont = lookup_fontname (specification,
1256 name,
1257 style)
1258 if new_resolved then
1259 resolved, subfont = new_resolved, new_subfont
1260 end
1261 end
1262
1263 if not resolved then
1264 if not fonts_reloaded and config.luaotfload.db.update_live == true then
1265 return reload_db (stringformat ("Font %q not found.",
1266 specification.name or "<?>"),
1267 lookup_font_name,
1268 specification)
1269 end
1270 end
1271 return resolved, subfont
1272 end
1273
1274 function lookup_fullpath (fontname, ext) --- getfilename()
1275 if not name_index then name_index = load_names () end
1276 local files = name_index.files
1277 local basedata = files.base
1278 local baredata = files.bare
1279 for i = 1, #location_precedence do
1280 local location = location_precedence [i]
1281 local basenames = basedata [location]
1282 local idx
1283 if basenames ~= nil then
1284 -- MK Added fallback
1285 idx = basenames [fontname]
1286 or casefold_search and basenames [stringlower(fontname)]
1287 -- /MK
1288 end
1289 if ext then
1290 local barenames = baredata [location] [ext]
1291 if not idx and barenames ~= nil then
1292 -- MK Added fallback
1293 idx = barenames [fontname]
1294 or casefold_search and barenames [stringlower(fontname)]
1295 -- /MK
1296 end
1297 end
1298 if idx then
1299 return files.full [idx]
1300 end
1301 end
1302 return ""
1303 end
1304
1305 --- when reload is triggered we update the database
1306 --- and then re-run the caller with the arg list
1307
1308 --- string -> ('a -> 'a) -> 'a list -> 'a
1309 function reload_db (why, caller, ...)
1310 local namedata = name_index
1311 local formats = tableconcat (namedata.meta.formats, ",")
1312
1313 logreport ("both", 0, "db",
1314 "Reload initiated (formats: %s); reason: %s",
1315 formats, why)
1316
1317 set_font_filter (formats)
1318 namedata = update_names (namedata, false, false)
1319
1320 if namedata then
1321 fonts_reloaded = true
1322 name_index = namedata
1323 return caller (...)
1324 end
1325
1326 logreport ("both", 0, "db", "Database update unsuccessful.")
1327 end
1328
1329 --- string -> string -> int
1330 local function iterative_levenshtein (s1, s2)
1331
1332 local costs = { }
1333 local len1, len2 = #s1, #s2
1334
1335 for i = 0, len1 do
1336 local last = i
1337 for j = 0, len2 do
1338 if i == 0 then
1339 costs[j] = j
1340 else
1341 if j > 0 then
1342 local current = costs[j-1]
1343 if stringsub(s1, i, i) ~= stringsub(s2, j, j) then
1344 current = mathmin(current, last, costs[j]) + 1
1345 end
1346 costs[j-1] = last
1347 last = current
1348 end
1349 end
1350 end
1351 if i > 0 then costs[len2] = last end
1352 end
1353
1354 return costs[len2]--- lower right has the distance
1355 end
1356
1357 --- string list -> string list
1358 local function delete_dupes (lst)
1359 local n0 = #lst
1360 if n0 == 0 then return lst end
1361 tablesort (lst)
1362 local ret = { }
1363 local last
1364 for i = 1, n0 do
1365 local cur = lst[i]
1366 if cur ~= last then
1367 last = cur
1368 ret[#ret + 1] = cur
1369 end
1370 end
1371 logreport (false, 8, "query",
1372 "Removed %d duplicate names.", n0 - #ret)
1373 return ret
1374 end
1375
1376 --- string -> int -> bool
1377 local function find_closest (name, limit)
1378 local name = sanitize_fontname (name)
1379 limit = limit or fuzzy_limit
1380
1381 if not name_index then name_index = load_names () end
1382 if not name_index or type (name_index) ~= "table" then
1383 if not fonts_reloaded then
1384 return reload_db("Font index missing.", find_closest, name)
1385 end
1386 return false
1387 end
1388
1389 local by_distance = { } --- (int, string list) dict
1390 local distances = { } --- int list
1391 local cached = { } --- (string, int) dict
1392 local mappings = name_index.mappings
1393 local n_fonts = #mappings
1394
1395 for n = 1, n_fonts do
1396 local current = mappings[n]
1397 --[[
1398 This is simplistic but surprisingly fast.
1399 Matching is performed against the “fullname” field
1400 of a db record in preprocessed form. We then store the
1401 raw “fullname” at its edit distance.
1402 We should probably do some weighting over all the
1403 font name categories as well as whatever agrep
1404 does.
1405 --]]
1406 local fullname = current.plainname
1407 local sfullname = current.fullname
1408 local dist = cached[sfullname]--- maybe already calculated
1409
1410 if not dist then
1411 dist = iterative_levenshtein(name, sfullname)
1412 cached[sfullname] = dist
1413 end
1414 local namelst = by_distance[dist]
1415 if not namelst then --- first entry
1416 namelst = { fullname }
1417 distances[#distances+1] = dist
1418 else --- append
1419 namelst[#namelst+1] = fullname
1420 end
1421
1422 by_distance[dist] = namelst
1423 end
1424
1425 --- print the matches according to their distance
1426 local n_distances = #distances
1427 if n_distances > 0 then --- got some data
1428 tablesort(distances)
1429 limit = mathmin(n_distances, limit)
1430 logreport (false, 1, "query",
1431 "Displaying %d distance levels.", limit)
1432
1433 for i = 1, limit do
1434 local dist = distances[i]
1435 local namelst = delete_dupes (by_distance[dist])
1436 logreport (false, 0, "query",
1437 "Distance from %q: %s\n "
1438 .. tableconcat (namelst, "\n "),
1439 name, dist)
1440 end
1441
1442 return true
1443 end
1444 return false
1445 end --- find_closest()
1446
1447 --- string -> uint -> bool * (string | rawdata)
1448 local function read_font_file (filename, subfont)
1449 local fontdata = otfhandler.readers.getinfo (filename,
1450 { subfont = subfont
1451 , platformnames = true
1452 , rawfamilynames = true
1453 })
1454 local msg = fontdata.comment
1455 if msg then
1456 return false, msg
1457 end
1458 return true, fontdata
1459 end
1460
1461 local function load_font_file (filename, subfont)
1462 local err, ret = read_font_file (filename, subfont)
1463 if err == false then
1464 logreport ("both", 1, "db", "ERROR: failed to open %q: %q.",
1465 tostring (filename), tostring (ret))
1466 return
1467 end
1468 return ret
1469 end
1470
1471 --- Design sizes in the fonts are specified in decipoints. For the
1472 --- index these values are prescaled to sp which is what we’re dealing
1473 --- with at the TeX end.
1474
1475 local get_size_info do --- too many upvalues :/
1476 --- rawdata -> (int * int * int | bool)
1477
1478 local sp = 2^16 -- pt
1479 local bp = 7227 / 7200 -- pt
1480
1481 function get_size_info (rawinfo)
1482 local design_size = rawinfo.design_size
1483 local design_range_top = rawinfo.design_range_top
1484 local design_range_bottom = rawinfo.design_range_bottom
1485
1486 local fallback_size = design_size ~= 0 and design_size
1487 or design_range_bottom ~= 0 and design_range_bottom
1488 or design_range_top ~= 0 and design_range_top
1489
1490 if fallback_size then
1491 design_size = ((design_size or fallback_size) * sp) / 10
1492 design_range_top = ((design_range_top or fallback_size) * sp) / 10
1493 design_range_bottom = ((design_range_bottom or fallback_size) * sp) / 10
1494
1495 design_size = design_size * bp
1496 design_range_top = design_range_top * bp
1497 design_range_bottom = design_range_bottom * bp
1498
1499 return {
1500 design_size, design_range_top, design_range_bottom,
1501 }
1502 end
1503
1504 return false
1505 end
1506 end ---[local get_size_info]
1507
1508 --[[doc--
1509 map_enlish_names -- Names-table for Lua fontloader objects. This
1510 may vanish eventually once we ditch Fontforge completely. Only
1511 subset of entries of that table are actually relevant so we’ll
1512 stick to that part.
1513 --doc]]--
1514
1515 local function get_english_names (metadata)
1516 local namesource
1517 local platformnames = metadata.platformnames
1518 --[[--
1519 Hans added the “platformnames” option for us to access parts of
1520 the original name table. The names are unreliable and
1521 completely disorganized, sure, but the Windows variant of the
1522 field often contains the superior information. Case in point:
1523
1524 ["platformnames"]={
1525 ["macintosh"]={
1526 ["compatiblefullname"]="Garamond Premr Pro Smbd It",
1527 ["family"]="Garamond Premier Pro",
1528 ["fullname"]="Garamond Premier Pro Semibold Italic",
1529 ["postscriptname"]="GaramondPremrPro-SmbdIt",
1530 ["subfamily"]="Semibold Italic",
1531 },
1532 ["windows"]={
1533 ["family"]="Garamond Premr Pro Smbd",
1534 ["fullname"]="GaramondPremrPro-SmbdIt",
1535 ["postscriptname"]="GaramondPremrPro-SmbdIt",
1536 ["subfamily"]="Italic",
1537 ["typographicfamily"]="Garamond Premier Pro",
1538 ["typographicsubfamily"]="Semibold Italic",
1539 },
1540 },
1541
1542 The essential bit is contained as “typographicfamily” (which we
1543 call for historical reasons the “preferred family”) and the
1544 “subfamily”. Only Why this is the case, only Adobe knows for
1545 certain.
1546 --]]--
1547 if platformnames then
1548 if platformnames.windows and platformnames.macintosh then
1549 return table.merge(platformnames.macintosh, platformnames.windows)
1550 end
1551 namesource = platformnames.windows or platformnames.macintosh
1552 end
1553 return namesource or metadata
1554 end
1555
1556 --[[--
1557 In case of broken PS names we set some dummies.
1558
1559 For this reason we copy what is necessary whilst keeping the table
1560 structure the same as in the tfmdata.
1561 --]]--
1562 local function get_raw_info (metadata, basename)
1563 local fontname = metadata.fontname
1564 local fullname = metadata.fullname
1565
1566 if not fontname or not fullname then
1567 --- Broken names table, e.g. avkv.ttf with UTF-16 strings;
1568 --- we put some dummies in place like the fontloader
1569 --- (font-otf.lua) does.
1570 logreport ("both", 3, "db",
1571 "Invalid names table of font %s, using dummies. \z
1572 Reported: fontname=%q, fullname=%q.",
1573 tostring (basename), tostring (fontname),
1574 tostring (fullname))
1575 fontname = "bad-fontname-" .. basename
1576 fullname = "bad-fullname-" .. basename
1577 end
1578
1579 return {
1580 familyname = metadata.familyname,
1581 fontname = fontname,
1582 fullname = fullname,
1583 italicangle = metadata.italicangle,
1584 names = metadata.names,
1585 units_per_em = metadata.units_per_em,
1586 version = metadata.version,
1587 design_size = metadata.design_size or metadata.designsize,
1588 design_range_top = metadata.design_range_top or metadata.maxsize,
1589 design_range_bottom = metadata.design_range_bottom or metadata.minsize,
1590 }
1591 end
1592
1593 local function organize_namedata (rawinfo,
1594 nametable,
1595 basename,
1596 info)
1597 local default_name = nametable.compatiblefullname
1598 or nametable.fullname
1599 or nametable.postscriptname
1600 or rawinfo.fullname
1601 or rawinfo.fontname
1602 or info.fullname
1603 or info.fontname
1604 local default_family = nametable.typographicfamily
1605 or nametable.family
1606 or rawinfo.familyname
1607 or info.familyname
1608 local fontnames = {
1609 --- see
1610 --- https://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html
1611 --- http://www.microsoft.com/typography/OTSPEC/name.htm#NameIDs
1612 english = {
1613 --- where a “compatiblefullname” field is given, the value
1614 --- of “fullname” is either identical or differs by
1615 --- separating the style with a hyphen and omitting spaces.
1616 --- (According to the spec, “compatiblefullname” is
1617 --- “Macintosh only”.) Of the three “fullname” fields, this
1618 --- one appears to be the one with the entire name given in
1619 --- a legible, non-abbreviated fashion, for most fonts at
1620 --- any rate. However, in some fonts (e.g. CMU) all three
1621 --- fields are identical.
1622 fullname = --[[ 18 ]] nametable.compatiblefullname
1623 or --[[ 4 ]] nametable.fullname
1624 or default_name,
1625 --- we keep both the “preferred family” and the “family”
1626 --- values around since both are valid but can turn out
1627 --- quite differently, e.g. with Latin Modern:
1628 --- typographicfamily: “Latin Modern Sans”,
1629 --- family: “LM Sans 10”
1630 family = --[[ 1 ]] nametable.family or default_family,
1631 subfamily = --[[ 2 ]] nametable.subfamily or rawinfo.subfamilyname,
1632 psname = --[[ 6 ]] nametable.postscriptname,
1633 typographicfamily = --[[ 16 ]] nametable.typographicfamily,
1634 typographicsubfamily = --[[ 17 ]] nametable.typographicsubfamily,
1635 },
1636
1637 metadata = {
1638 fullname = rawinfo.fullname,
1639 fontname = rawinfo.fontname,
1640 familyname = rawinfo.familyname,
1641 },
1642
1643 info = {
1644 fullname = info.fullname,
1645 familyname = info.familyname,
1646 fontname = info.fontname,
1647 },
1648 }
1649
1650 return {
1651 sanitized = sanitize_fontnames (fontnames),
1652 fontname = rawinfo.fontname,
1653 fullname = rawinfo.fullname,
1654 familyname = rawinfo.familyname,
1655 }
1656 end
1657
1658
1659 local dashsplitter = lpegsplitat "-"
1660
1661 local function split_fontname (fontname)
1662 --- sometimes the style hides in the latter part of the
1663 --- fontname, separated by a dash, e.g. “Iwona-Regular”,
1664 --- “GFSSolomos-Regular”
1665 local splitted = { lpegmatch (dashsplitter, fontname) }
1666 if next (splitted) then
1667 return sanitize_fontname (splitted [#splitted])
1668 end
1669 end
1670
1671 local function organize_styledata (metadata, rawinfo)
1672 local pfminfo = metadata.pfminfo
1673 local names = rawinfo.names
1674 return {
1675 --- see http://www.microsoft.com/typography/OTSPEC/features_pt.htm#size
1676 size = get_size_info (rawinfo),
1677 pfmweight = pfminfo and pfminfo.weight or metadata.pfmweight or 400,
1678 weight = rawinfo.weight or metadata.weight or "unspecified",
1679 split = split_fontname (rawinfo.fontname),
1680 width = pfminfo and pfminfo.width or metadata.pfmwidth,
1681 italicangle = metadata.italicangle,
1682 --- this is for querying, see www.ntg.nl/maps/40/07.pdf for details
1683 units_per_em = metadata.units_per_em or metadata.units,
1684 version = metadata.version,
1685 }
1686 end
1687
1688 --[[doc--
1689 The data inside an Opentype font file can be quite heterogeneous.
1690 Thus in order to get the relevant information, parts of the original
1691 table as returned by the font file reader need to be relocated.
1692 --doc]]--
1693
1694 --- string -> int -> bool -> string -> fontentry
1695
1696 local function ot_fullinfo (filename,
1697 subfont,
1698 location,
1699 basename,
1700 format,
1701 info)
1702
1703 local metadata = load_font_file (filename, subfont)
1704 if not metadata then
1705 return nil
1706 end
1707
1708 local rawinfo = get_raw_info (metadata, basename)
1709 local nametable = get_english_names (metadata)
1710 local namedata = organize_namedata (rawinfo,
1711 nametable,
1712 basename,
1713 info)
1714 local style = organize_styledata (metadata,
1715 rawinfo)
1716 local res = {
1717 file = { base = basename,
1718 full = filename,
1719 subfont = subfont,
1720 location = location or "system" },
1721 format = format,
1722 names = namedata,
1723 style = style,
1724 version = rawinfo.version,
1725 }
1726 return res
1727 end
1728
1729 --[[doc--
1730
1731 Type1 font inspector. In comparison with OTF, PFB’s contain a good
1732 deal less name fields which makes it tricky in some parts to find a
1733 meaningful representation for the database.
1734
1735 Good read: http://www.adobe.com/devnet/font/pdfs/5004.AFM_Spec.pdf
1736
1737 --doc]]--
1738
1739 --- string -> int -> bool -> string -> fontentry
1740
1741 local function t1_fullinfo (filename, _subfont, location, basename, format)
1742 local sanitized
1743 local metadata = load_font_file (filename)
1744 local fontname = metadata.fontname
1745 local fullname = metadata.fullname
1746 local familyname = metadata.familyname
1747 local italicangle = metadata.italicangle
1748 local style = ""
1749 local weight
1750
1751 sanitized = sanitize_fontnames ({
1752 fontname = fontname,
1753 psname = fullname,
1754 familyname = familyname,
1755 weight = metadata.weight, --- string identifier
1756 typographicsubfamily = style,
1757 })
1758
1759 weight = sanitized.weight
1760
1761 if weight == "bold" then
1762 style = weight
1763 end
1764
1765 if italicangle ~= 0 then
1766 style = style .. "italic"
1767 end
1768
1769 return {
1770 basename = basename,
1771 fullpath = filename,
1772 subfont = false,
1773 location = location or "system",
1774 format = format,
1775 fullname = sanitized.fullname,
1776 fontname = sanitized.fontname,
1777 familyname = sanitized.familyname,
1778 plainname = fullname,
1779 psname = sanitized.fontname,
1780 version = metadata.version,
1781 size = false,
1782 typographicsubfamily = style ~= "" and style or weight,
1783 weight = metadata.pfminfo and pfminfo.weight or 400,
1784 italicangle = italicangle,
1785 }
1786 end
1787
1788 local loaders = {
1789 otf = ot_fullinfo,
1790 ttc = ot_fullinfo,
1791 ttf = ot_fullinfo,
1792 afm = t1_fullinfo,
1793 pfb = t1_fullinfo,
1794 }
1795
1796 --- not side-effect free!
1797
1798 local function compare_timestamps (fullname,
1799 currentstatus,
1800 currententrystatus,
1801 currentmappings,
1802 targetstatus,
1803 targetentrystatus,
1804 targetmappings)
1805
1806 local currenttimestamp = currententrystatus
1807 and currententrystatus.timestamp
1808 local targettimestamp = lfsattributes (fullname, "modification")
1809
1810 if targetentrystatus ~= nil
1811 and targetentrystatus.timestamp == targettimestamp then
1812 logreport ("log", 3, "db", "Font %q already read.", fullname)
1813 return false
1814 end
1815
1816 targetentrystatus.timestamp = targettimestamp
1817 targetentrystatus.index = targetentrystatus.index or { }
1818
1819 if currenttimestamp == targettimestamp
1820 and not targetentrystatus.index [1]
1821 then
1822 --- copy old namedata into new
1823
1824 for _, currentindex in next, currententrystatus.index do
1825
1826 local targetindex = #targetentrystatus.index
1827 local fullinfo = currentmappings [currentindex]
1828 local location = #targetmappings + 1
1829
1830 targetmappings [location] = fullinfo
1831 targetentrystatus.index [targetindex + 1] = location
1832 end
1833
1834 logreport ("log", 3, "db", "Font %q already indexed.", fullname)
1835
1836 return false
1837 end
1838
1839 return true
1840 end
1841
1842 local function insert_fullinfo (fullname,
1843 basename,
1844 n_font,
1845 loader,
1846 format,
1847 location,
1848 targetmappings,
1849 targetentrystatus,
1850 info)
1851
1852 local fullinfo = loader (fullname, n_font,
1853 location, basename,
1854 format, info)
1855
1856 if not fullinfo then
1857 return false
1858 end
1859
1860 local index = targetentrystatus.index [n_font]
1861
1862 if not index then
1863 index = #targetmappings + 1
1864 end
1865
1866 targetmappings [index] = fullinfo
1867 targetentrystatus.index [n_font] = index
1868
1869 return true
1870 end
1871
1872
1873
1874 --- we return true if the font is new or re-indexed
1875 --- string -> dbobj -> dbobj -> bool
1876
1877 local function read_font_names (fullname,
1878 currentnames,
1879 targetnames,
1880 location)
1881
1882 local targetmappings = targetnames.mappings
1883 local targetstatus = targetnames.status --- by full path
1884 local targetentrystatus = targetstatus [fullname]
1885
1886 if targetentrystatus == nil then
1887 targetentrystatus = { }
1888 targetstatus [fullname] = targetentrystatus
1889 end
1890
1891 local currentmappings = currentnames.mappings
1892 local currentstatus = currentnames.status
1893 local currententrystatus = currentstatus [fullname]
1894
1895 local basename = filebasename (fullname)
1896 local barename = filenameonly (fullname)
1897 local entryname = fullname
1898
1899 if location == "texmf" then
1900 entryname = basename
1901 end
1902
1903 --- 1) skip if blacklisted
1904
1905 if names.blacklist[fullname] or names.blacklist[basename] then
1906 logreport ("log", 2, "db",
1907 "Ignoring blacklisted font %q.", fullname)
1908 return false
1909 end
1910
1911 --- 2) skip if known with same timestamp
1912
1913 if not compare_timestamps (fullname,
1914 currentstatus,
1915 currententrystatus,
1916 currentmappings,
1917 targetstatus,
1918 targetentrystatus,
1919 targetmappings)
1920 then
1921 return false
1922 end
1923
1924 --- 3) new font; choose a loader, abort if unknown
1925
1926 local format = stringlower (filesuffix (basename))
1927 local loader = loaders [format] --- ot_fullinfo, t1_fullinfo
1928
1929 if not loader then
1930 logreport ("both", 0, "db",
1931 "Unknown format: %q, skipping.", format)
1932 return false
1933 end
1934
1935 --- 4) get basic info, abort if fontloader can’t read it
1936
1937 local err, info = read_font_file (fullname)
1938
1939 if err == false then
1940 logreport ("log", 1, "db",
1941 "Failed to read basic information from %q: %q",
1942 basename, tostring (info))
1943 return false
1944 end
1945
1946
1947 --- 5) check for subfonts and process each of them
1948
1949 if type (info) == "table" and #info >= 1 then --- ttc
1950
1951 local success = false --- true if at least one subfont got read
1952
1953 for n_font = 1, #info do
1954 if insert_fullinfo (fullname, basename, n_font,
1955 loader, format, location,
1956 targetmappings, targetentrystatus,
1957 info[n_font])
1958 then
1959 success = true
1960 end
1961 end
1962
1963 return success
1964 end
1965
1966 return insert_fullinfo (fullname, basename, false,
1967 loader, format, location,
1968 targetmappings, targetentrystatus,
1969 info)
1970 end
1971
1972 local path_normalize
1973 do
1974 --- os.type and os.name are constants so we
1975 --- choose a normalization function in advance
1976 --- instead of testing with every call
1977 local os_type, os_name = os.type, os.name
1978 local filecollapsepath = file.collapsepath or file.collapse_path
1979
1980 --- windows and dos
1981 if os_type == "windows" or os_type == "msdos" then
1982 --- ms platform specific stuff
1983 function path_normalize (path)
1984 path = stringgsub(path, '\\', '/')
1985 path = stringlower(path)
1986 path = filecollapsepath(path)
1987 return path
1988 end
1989 --[[doc--
1990 The special treatment for cygwin was removed with a patch submitted
1991 by Ken Brown.
1992 Reference: http://cygwin.com/ml/cygwin/2013-05/msg00006.html
1993 --doc]]--
1994
1995 else -- posix
1996 path_normalize = filecollapsepath
1997 end
1998 end
1999
2000 local blacklist = { }
2001 local p_blacklist --- prefixes of dirs
2002
2003 --- string list -> string list
2004 local function collapse_prefixes (lst)
2005 --- avoid redundancies in blacklist
2006 if #lst < 2 then
2007 return lst
2008 end
2009
2010 tablesort(lst)
2011 local cur = lst[1]
2012 local result = { cur }
2013 for i=2, #lst do
2014 local elm = lst[i]
2015 if stringsub(elm, 1, #cur) ~= cur then
2016 --- different prefix
2017 cur = elm
2018 result[#result+1] = cur
2019 end
2020 end
2021 return result
2022 end
2023
2024 --- string list -> string list -> (string, bool) hash_t
2025 local function create_blacklist (blacklist, whitelist)
2026 local result = { }
2027 local dirs = { }
2028
2029 logreport ("info", 2, "db", "Blacklisting %d files and directories.",
2030 #blacklist)
2031 for i=1, #blacklist do
2032 local entry = blacklist[i]
2033 if lfsisdir(entry) then
2034 dirs[#dirs+1] = entry
2035 else
2036 result[blacklist[i]] = true
2037 end
2038 end
2039
2040 logreport ("info", 2, "db", "Whitelisting %d files.", #whitelist)
2041 for i=1, #whitelist do
2042 result[whitelist[i]] = nil
2043 end
2044
2045 dirs = collapse_prefixes(dirs)
2046
2047 --- build the disjunction of the blacklisted directories
2048 for i=1, #dirs do
2049 local p_dir = P(dirs[i])
2050 if p_blacklist then
2051 p_blacklist = p_blacklist + p_dir
2052 else
2053 p_blacklist = p_dir
2054 end
2055 end
2056
2057 if p_blacklist == nil then
2058 --- always return false
2059 p_blacklist = lpeg.Cc(false)
2060 end
2061
2062 return result
2063 end
2064
2065 --- unit -> unit
2066 local function read_blacklist ()
2067 local files = {
2068 kpselookup ("luaotfload-blacklist.cnf",
2069 {all=true, format="tex"})
2070 }
2071 local blacklist = { }
2072 local whitelist = { }
2073
2074 if files and type(files) == "table" then
2075 for _, path in next, files do
2076 for line in iolines (path) do
2077 line = stringstrip(line) -- to get rid of lines like " % foo"
2078 local first_chr = stringsub(line, 1, 1)
2079 if first_chr == "%" or stringis_empty(line) then
2080 -- comment or empty line
2081 elseif first_chr == "-" then
2082 logreport ("both", 3, "db",
2083 "Whitelisted file %q via %q.",
2084 line, path)
2085 whitelist[#whitelist+1] = stringsub(line, 2, -1)
2086 else
2087 local cmt = stringfind(line, "%%")
2088 if cmt then
2089 line = stringsub(line, 1, cmt - 1)
2090 end
2091 line = stringstrip(line)
2092 logreport ("both", 3, "db",
2093 "Blacklisted file %q via %q.",
2094 line, path)
2095 blacklist[#blacklist+1] = line
2096 end
2097 end
2098 end
2099 end
2100 names.blacklist = create_blacklist(blacklist, whitelist)
2101 end
2102
2103 local p_font_filter
2104
2105 do
2106 local function extension_pattern (list)
2107 if type (list) ~= "table" or #list == 0 then return P(-1) end
2108 local pat
2109 for i=#list, 1, -1 do
2110 local e = list[i]
2111 if not pat then
2112 pat = P(e)
2113 else
2114 pat = pat + P(e)
2115 end
2116 end
2117 pat = pat * P(-1)
2118 return (1 - pat)^1 * pat
2119 end
2120
2121 --- small helper to adjust the font filter pattern (--formats
2122 --- option)
2123
2124 local current_formats = { }
2125
2126 local splitcomma = luaotfload.parsers.splitcomma
2127 function set_font_filter (formats)
2128
2129 if not formats or type (formats) ~= "string" then
2130 return
2131 end
2132
2133 if stringsub (formats, 1, 1) == "+" then -- add
2134 formats = lpegmatch (splitcomma, stringsub (formats, 2))
2135 if formats then
2136 current_formats = tableappend (current_formats, formats)
2137 end
2138 elseif stringsub (formats, 1, 1) == "-" then -- remove
2139 formats = lpegmatch (splitcomma, stringsub (formats, 2))
2140 if formats then
2141 local newformats = { }
2142 for i = 1, #current_formats do
2143 local fmt = current_formats[i]
2144 for j = 1, #formats do
2145 if current_formats[i] == formats[j] then
2146 goto skip
2147 end
2148 end
2149 newformats[#newformats+1] = fmt
2150 ::skip::
2151 end
2152 current_formats = newformats
2153 end
2154 else -- set
2155 formats = lpegmatch (splitcomma, formats)
2156 if formats then
2157 current_formats = formats
2158 end
2159 end
2160
2161 p_font_filter = extension_pattern (current_formats)
2162 end
2163
2164 function get_font_filter (formats)
2165 return tablefastcopy (current_formats)
2166 end
2167 end
2168
2169 local function locate_matching_pfb (afmfile, dir)
2170 local pfbname = filereplacesuffix (afmfile, "pfb")
2171 local pfbpath = dir .. "/" .. pfbname
2172 if lfsisfile (pfbpath) then
2173 return pfbpath
2174 end
2175 --- Check for match in texmf too
2176 return kpsefind_file (pfbname, "type1 fonts")
2177 end
2178
2179 local function process_dir_tree (acc, dirs, done)
2180 if not next (dirs) then --- done
2181 return acc
2182 end
2183
2184 local dir = dirs[#dirs]
2185 dirs[#dirs] = nil
2186
2187 local mode_or_err
2188 dir, mode_or_err = realpath(dir)
2189 if not dir then
2190 logreport ("both", 1, "db", "Skipping font directory: %s", mode_or_err)
2191 return process_dir_tree (acc, dirs, done)
2192 elseif mode_or_err ~= 'directory' then
2193 logreport ("both", 1, "db", "Skipping non-directory while searching fonts: %q (%s)", dir, mode_or_err)
2194 return process_dir_tree (acc, dirs, done)
2195 end
2196
2197 if tablecontains (done, dir) then
2198 --- Already traversed. Note that it’d be unsafe to rely on the
2199 --- hash part above due to Lua only processing up to 32 bytes
2200 --- of string data. The lookup shouldn’t impact performance too
2201 --- much but we could check the performance of alternative data
2202 --- structures at some point.
2203 return process_dir_tree (acc, dirs, done)
2204 end
2205
2206 local newfiles = { }
2207 local blacklist = names.blacklist
2208 for ent in lfsdir (dir) do
2209 --- filter right away
2210 if ent ~= "." and ent ~= ".." and not blacklist[ent] then
2211 local fullpath = dir .. "/" .. ent
2212 if lfsisdir (fullpath)
2213 and not lpegmatch (p_blacklist, fullpath)
2214 then
2215 dirs[#dirs+1] = fullpath
2216 elseif lfsisfile (fullpath) then
2217 ent = stringlower (ent)
2218 if lpegmatch (p_font_filter, ent) then
2219 if filesuffix (ent) == "afm" then
2220 local pfbpath = locate_matching_pfb (ent, dir)
2221 if pfbpath then
2222 newfiles[#newfiles+1] = pfbpath
2223 end
2224 end
2225 newfiles[#newfiles+1] = fullpath
2226 end
2227 end
2228 end
2229 end
2230 done [#done + 1] = dir
2231 return process_dir_tree (tableappend (acc, newfiles), dirs, done)
2232 end
2233
2234 local function process_dir (dir)
2235 local mode_or_err
2236 dir, mode_or_err = realpath(dir)
2237 if not dir then
2238 logreport ("both", 1, "db", "Skipping font directory: %s", mode_or_err)
2239 return {}
2240 elseif mode_or_err ~= 'directory' then
2241 logreport ("both", 1, "db", "Skipping non-directory while searching fonts: %q (%s)", dir, mode_or_err)
2242 return {}
2243 end
2244
2245 local files = { }
2246 local blacklist = names.blacklist
2247 for ent in lfsdir (dir) do
2248 if ent ~= "." and ent ~= ".." and not blacklist[ent] then
2249 local fullpath = dir .. "/" .. ent
2250 if lfsisfile (fullpath) then
2251 ent = stringlower (ent)
2252 if lpegmatch (p_font_filter, ent)
2253 then
2254 if filesuffix (ent) == "afm" then
2255 local pfbpath = locate_matching_pfb (ent, dir)
2256 if pfbpath then
2257 files[#files+1] = pfbpath
2258 end
2259 else
2260 files[#files+1] = fullpath
2261 end
2262 end
2263 end
2264 end
2265 end
2266 return files
2267 end
2268
2269 --- string -> bool -> string list
2270 local function find_font_files (root, recurse)
2271 if lfsisdir (root) then
2272 if recurse == true then
2273 return process_dir_tree ({}, { root }, {})
2274 else --- kpathsea already delivered the necessary subdirs
2275 return process_dir (root)
2276 end
2277 end
2278 end
2279
2280 --- truncate_string -- Cut the first part of a string to fit it
2281 --- into a given terminal width. The parameter “restrict” (int)
2282 --- indicates the number of characters already consumed on the
2283 --- line.
2284 local function truncate_string (str, restrict)
2285 local tw = config.luaotfload.misc.termwidth
2286 local wd = tw - restrict
2287 local len = utf8len (str)
2288 if not len then
2289 -- str is not valid UTF-8... We will assume a 8-bit
2290 -- encoding and forward it verbatim to the output.
2291 len = #str
2292 if wd - len < 0 then
2293 str = ".." .. stringsub(str, len - wd + 2)
2294 end
2295 elseif wd - len < 0 then
2296 --- combined length exceeds terminal,
2297 str = ".." .. stringsub(str, utf8offset(str, - wd + 2))
2298 end
2299 return str
2300 end
2301
2302
2303 --[[doc--
2304
2305 collect_font_filenames_dir -- Traverse the directory root at
2306 ``dirname`` looking for font files. Returns a list of {*filename*;
2307 *location*} pairs.
2308
2309 --doc]]--
2310
2311 --- string -> string -> string * string list
2312 local function collect_font_filenames_dir (dirname, location)
2313 if lpegmatch (p_blacklist, dirname) then
2314 logreport ("both", 4, "db",
2315 "Skipping blacklisted directory %s.", dirname)
2316 --- ignore
2317 return { }
2318 end
2319 local found = find_font_files (dirname, location ~= "texmf" and location ~= "local")
2320 if not found then
2321 logreport ("both", 4, "db",
2322 "No such directory: %q; skipping.", dirname)
2323 return { }
2324 end
2325
2326 local nfound = #found
2327 local files = { }
2328
2329 logreport ("both", 4, "db",
2330 "%d font files detected in %s.",
2331 nfound, dirname)
2332 for j = 1, nfound do
2333 local fullname = found[j]
2334 files[#files + 1] = { path_normalize (fullname), location }
2335 end
2336 return files
2337 end
2338
2339 local stripslashes = luaotfload.parsers.stripslashes
2340 --- string list -> string list
2341 local function filter_out_pwd (dirs)
2342 local result = { }
2343 local pwd = path_normalize (lpegmatch (stripslashes,
2344 lfscurrentdir ()))
2345 for i = 1, #dirs do
2346 --- better safe than sorry
2347 local dir = path_normalize (lpegmatch (stripslashes, dirs[i]))
2348 if dir == "." or dir == pwd then
2349 logreport ("both", 3, "db",
2350 "Path %q matches $PWD (%q), skipping.",
2351 dir, pwd)
2352 else
2353 result[#result+1] = dir
2354 end
2355 end
2356 return result
2357 end
2358
2359 local path_separator = os.type == "windows" and ";" or ":"
2360
2361 --[[doc--
2362
2363 collect_font_filenames_texmf -- Scan texmf tree for font files
2364 relying on kpathsea search paths for the respective file types.
2365 The current working directory comes as “.” (texlive) or absolute
2366 path (miktex) and will always be filtered out.
2367
2368 Returns a list of { *filename*; *location* } pairs.
2369
2370 --doc]]--
2371
2372 --- unit -> string * string list
2373 local function collect_font_filenames_texmf ()
2374
2375 local osfontdir = kpseexpand_path "$OSFONTDIR"
2376
2377 if stringis_empty (osfontdir) then
2378 logreport ("both", 1, "db", "Scanning TEXMF for fonts...")
2379 else
2380 logreport ("both", 1, "db", "Scanning TEXMF and $OSFONTDIR for fonts...")
2381 if log.get_loglevel () > 3 then
2382 local osdirs = filesplitpath (osfontdir)
2383 logreport ("both", 0, "db", "$OSFONTDIR has %d entries:", #osdirs)
2384 for i = 1, #osdirs do
2385 logreport ("both", 0, "db", "[%d] %s", i, osdirs[i])
2386 end
2387 end
2388 end
2389
2390 local show_path = kpse.show_path
2391
2392 local function expanded_path (file_type)
2393 return kpseexpand_path (show_path (file_type))
2394 end
2395
2396 local fontdirs = expanded_path "opentype fonts"
2397 fontdirs = fontdirs .. path_separator .. expanded_path "truetype fonts"
2398 fontdirs = fontdirs .. path_separator .. expanded_path "type1 fonts"
2399 fontdirs = fontdirs .. path_separator .. expanded_path "afm"
2400
2401 fontdirs = filesplitpath (fontdirs) or { }
2402
2403 local tasks = filter_out_pwd (fontdirs)
2404 logreport ("both", 3, "db",
2405 "Initiating scan of %d directories.", #tasks)
2406
2407 local files = { }
2408 for _, dir in next, tasks do
2409 files = tableappend (files, collect_font_filenames_dir (dir, "texmf"))
2410 end
2411 logreport ("both", 3, "db", "Collected %d files.", #files)
2412 return files
2413 end
2414
2415 --- unit -> string list
2416 local function get_os_dirs ()
2417 if os.name == 'macosx' then
2418 return {
2419 filejoin(kpseexpand_path('~'), "Library/Fonts"),
2420 "/Library/Fonts",
2421 "/System/Library/Fonts",
2422 "/Network/Library/Fonts",
2423 }
2424 elseif os.type == "windows" or os.type == "msdos" then
2425 local windir = osgetenv("WINDIR")
2426 local appdata = osgetenv("LOCALAPPDATA")
2427 if chgstrcp and kpse.var_value('command_line_encoding') ~= nil then
2428 return { filejoin(windir, 'Fonts'), chgstrcp.syscptoutf8(filejoin(appdata, 'Microsoft/Windows/Fonts')) }
2429 else
2430 return { filejoin(windir, 'Fonts'), filejoin(appdata, 'Microsoft/Windows/Fonts') }
2431 end
2432 else
2433 local fonts_conves = { --- plural, much?
2434 "/usr/local/etc/fonts/fonts.conf",
2435 "/etc/fonts/fonts.conf",
2436 }
2437 local os_dirs = luaotfload.parsers.read_fonts_conf(fonts_conves, find_files)
2438 return os_dirs
2439 end
2440 return {}
2441 end
2442
2443 --[[doc--
2444
2445 count_removed -- Count paths that do not exist in the file system.
2446
2447 --doc]]--
2448
2449 --- string list -> size_t
2450 local function count_removed (files)
2451 if not files or not files.full then
2452 logreport ("log", 4, "db", "Empty file store; no data to work with.")
2453 return 0
2454 end
2455 local old = files.full
2456 logreport ("log", 4, "db", "Checking removed files.")
2457 local nrem = 0
2458 local nold = #old
2459 for i = 1, nold do
2460 local f = old[i]
2461 if not kpsereadable_file (f) then
2462 logreport ("log", 2, "db",
2463 "File %q does not exist in file system.", f)
2464 nrem = nrem + 1
2465 end
2466 end
2467 return nrem
2468 end
2469
2470 --[[doc--
2471
2472 retrieve_namedata -- Scan the list of collected fonts and populate
2473 the list of namedata.
2474
2475 · dirname : name of the directory to scan
2476 · currentnames : current font db object
2477 · targetnames : font db object to fill
2478 · dry_run : don’t touch anything
2479
2480 Returns the number of fonts that were actually added to the index.
2481
2482 --doc]]--
2483
2484 --- string * string list -> dbobj -> dbobj -> bool? -> int * int
2485 local function retrieve_namedata (files, currentnames, targetnames, dry_run)
2486
2487 local nfiles = #files
2488 local nnew = 0
2489
2490 logreport ("info", 1, "db", "Scanning %d collected font files ...", nfiles)
2491
2492 local bylocation = { texmf = { 0, 0 }
2493 , ["local"] = { 0, 0 }
2494 , system = { 0, 0 }
2495 }
2496 report_status_start (2, 4)
2497 for i = 1, nfiles do
2498 local fullname, location = unpack (files[i])
2499 local count = bylocation[location]
2500 count[1] = count[1] + 1
2501 if dry_run == true then
2502 local truncated = truncate_string (fullname, 43)
2503 logreport ("log", 2, "db", "Would have been loading %s.", fullname)
2504 report_status ("term", "db", "Would have been loading %s", truncated)
2505 --- skip the read_font_names part
2506 else
2507 local truncated = truncate_string (fullname, 32)
2508 logreport ("log", 2, "db", "Loading font %s.", fullname)
2509 report_status ("term", "db", "Loading font %s", truncated)
2510 local new = read_font_names (fullname, currentnames,
2511 targetnames, location)
2512 if new == true then
2513 nnew = nnew + 1
2514 count[2] = count[2] + 1
2515 end
2516 end
2517 end
2518 report_status_stop ("term", "db", "Scanned %d files, %d new.", nfiles, nnew)
2519 for location, count in next, bylocation do
2520 logreport ("term", 4, "db", " * %s: %d files, %d new",
2521 location, count[1], count[2])
2522 end
2523 return nnew
2524 end
2525
2526 --- unit -> string * string list
2527 local function collect_font_filenames_system ()
2528
2529 local n_scanned, n_new = 0, 0
2530 logreport ("info", 1, "db", "Scanning system fonts...")
2531 logreport ("info", 2, "db",
2532 "Searching in static system directories...")
2533
2534 local files = { }
2535 for _, dir in next, get_os_dirs () do
2536 tableappend (files, collect_font_filenames_dir (dir, "system"))
2537 end
2538 logreport ("term", 3, "db", "Collected %d files.", #files)
2539 return files
2540 end
2541
2542 --- unit -> bool
2543 local function flush_lookup_cache ()
2544 lookup_cache = { }
2545 collectgarbage "collect"
2546 return true
2547 end
2548
2549 --[[doc--
2550
2551 collect_font_filenames_local -- Scan $PWD (during a TeX run)
2552 for font files.
2553
2554 Side effect: This sets the “local” flag in the subtable “meta” to
2555 prevent the merged table from being saved to disk.
2556
2557 TODO the local tree could be cached in $PWD.
2558
2559 --doc]]--
2560
2561 --- unit -> string * string list
2562 local function collect_font_filenames_local ()
2563 local pwd = lfscurrentdir ()
2564 logreport ("both", 1, "db", "Scanning for fonts in $PWD (%q) ...", pwd)
2565
2566 local files = collect_font_filenames_dir (pwd, "local")
2567 local nfiles = #files
2568 if nfiles > 0 then
2569 logreport ("term", 1, "db", "Found %d files.", pwd)
2570 else
2571 logreport ("term", 1, "db",
2572 "Couldn’t find a thing here. What a waste.", pwd)
2573 end
2574 logreport ("term", 3, "db", "Collected %d files.", #files)
2575 return files, nfiles > 0
2576 end
2577
2578 --- fontentry list -> filemap
2579 local function generate_filedata (mappings)
2580
2581 logreport ("both", 2, "db", "Creating filename map.")
2582
2583 local nmappings = #mappings
2584
2585 local files = {
2586 bare = {
2587 ["local"] = { },
2588 system = { }, --- mapped to mapping format -> index in full
2589 texmf = { }, --- mapped to mapping format -> “true”
2590 },
2591 base = {
2592 ["local"] = { },
2593 system = { }, --- mapped to index in “full”
2594 texmf = { }, --- set; all values are “true”
2595 },
2596 full = { }, --- non-texmf
2597 }
2598
2599 local base = files.base
2600 local bare = files.bare
2601 local full = files.full
2602
2603 local conflicts = {
2604 basenames = 0,
2605 barenames = 0,
2606 }
2607
2608 for index = 1, nmappings do
2609 local entry = mappings [index]
2610 local filedata = entry.file
2611 local format
2612 local location
2613 local fullpath
2614 local basename
2615 local barename
2616 local subfont
2617
2618 if filedata then --- new entry
2619 format = entry.format --- otf, afm, ...
2620 location = filedata.location --- texmf, system, ...
2621 fullpath = filedata.full
2622 basename = filedata.base
2623 barename = filenameonly (fullpath)
2624 subfont = filedata.subfont
2625 else
2626 format = entry.format --- otf, afm, ...
2627 location = entry.location --- texmf, system, ...
2628 fullpath = entry.fullpath
2629 basename = entry.basename
2630 barename = filenameonly (fullpath)
2631 subfont = entry.subfont
2632 end
2633
2634 entry.index = index
2635
2636 --- 1) add to basename table
2637
2638 local inbase = base [location] --- no format since the suffix is known
2639
2640 -- MK Added lowercase versions for case-insensitive fallback
2641 if inbase then
2642 local present = inbase [basename]
2643 if present then
2644 logreport ("both", 4, "db",
2645 "Conflicting basename: %q already indexed \z
2646 in category %s, ignoring.",
2647 barename, location)
2648 conflicts.basenames = conflicts.basenames + 1
2649
2650 --- track conflicts per font
2651 local conflictdata = entry.conflicts
2652
2653 if not conflictdata then
2654 entry.conflicts = { basename = present }
2655 else -- some conflicts already detected
2656 conflictdata.basename = present
2657 end
2658
2659 else
2660 local lowerbasename = stringlower (basename)
2661 if basename ~= lowerbasename then
2662 present = inbase [lowerbasename]
2663 if present then
2664 logreport ("both", 4, "db",
2665 "Conflicting basename: %q already indexed \z
2666 as %s.",
2667 barename, mappings[present].basename)
2668 conflicts.basenames = conflicts.basenames + 1
2669
2670 --- track conflicts per font
2671 local conflictdata = entry.conflicts
2672
2673 if not conflictdata then
2674 entry.conflicts = { basename = present }
2675 else -- some conflicts already detected
2676 conflictdata.basename = present
2677 end
2678
2679 else
2680 inbase [lowerbasename] = index
2681 end
2682 end
2683 inbase [basename] = index
2684 end
2685 else
2686 inbase = { basename = index }
2687 base [location] = inbase
2688 local lowerbasename = stringlower (basename)
2689 if basename ~= lowerbasename then
2690 inbase [lowerbasename] = index
2691 end
2692 end
2693
2694 --- 2) add to barename table
2695
2696 local inbare = bare [location] [format]
2697
2698 if inbare then
2699 local present = inbare [barename]
2700 if present then
2701 logreport ("both", 4, "db",
2702 "Conflicting barename: %q already indexed \z
2703 in category %s/%s, ignoring.",
2704 barename, location, format)
2705 conflicts.barenames = conflicts.barenames + 1
2706
2707 --- track conflicts per font
2708 local conflictdata = entry.conflicts
2709
2710 if not conflictdata then
2711 entry.conflicts = { barename = present }
2712 else -- some conflicts already detected
2713 conflictdata.barename = present
2714 end
2715 else
2716 local lowerbarename = stringlower (barename)
2717 if barename ~= lowerbarename then
2718 present = inbare [lowerbarename]
2719 if present then
2720 logreport ("both", 4, "db",
2721 "Conflicting barename: %q already indexed \z
2722 as %s.",
2723 barename, mappings[present].basename)
2724 conflicts.barenames = conflicts.barenames + 1
2725
2726 --- track conflicts per font
2727 local conflictdata = entry.conflicts
2728
2729 if not conflictdata then
2730 entry.conflicts = { barename = present }
2731 else -- some conflicts already detected
2732 conflictdata.barename = present
2733 end
2734 else
2735 inbare [lowerbarename] = index
2736 end
2737 end
2738 inbare [barename] = index
2739 end
2740 else
2741 inbare = { [barename] = index }
2742 bare [location] [format] = inbare
2743 local lowerbarename = stringlower (barename)
2744 if barename ~= lowerbarename then
2745 inbare [lowerbarename] = index
2746 end
2747 end
2748 -- /MK
2749
2750 --- 3) add to fullpath map
2751
2752 full [index] = fullpath
2753 end --- mapping traversal
2754
2755 return files
2756 end
2757
2758 local function regular_score(entry)
2759 return 10000 * (entry.italicangle or 0)^2 -- We really don't want italic fonts here (italic font have an angle around 10)
2760 + .01 * ((entry.pfmweight or 400) - 400)^2 -- weights are normally multiples of 100, so they are still quite large after .01
2761 + ((entry.width or 5) - 5)^2
2762 + (regular_synonym[entry.subfamily or entry.typographicsubfamily] or 1000000)
2763 + (entry.pfmweight > 500 and 1000 or 0)
2764 end
2765 local function italic_score(entry, regular_entry)
2766 local regularangle = regular_entry.italicangle or 0
2767 local angle = entry.italicangle or 0
2768 if (angle == 0 or angle == regularangle)
2769 and (entry.subfamily == regular_entry.subfamily or style_synonym[entry.subfamily] ~= 'i') then
2770 return -- This font is not italic in any way
2771 end
2772 return .1 * (angle - regularangle - 10)^2 -- Should there ever be multiple levels of italicness...
2773 + 0.1 * ((entry.pfmweight or 400) - (regular_entry.pfmweight or 400))^2 -- weights are normally multiples of 100, so they are still quite large after .01
2774 + ((entry.width or 5) - regular_entry.width)^2
2775 + (style_synonym[entry.subfamily or entry.typographicsubfamily] == 'i' and 0 or 1000000)
2776 end
2777 local function bold_score(entry, regular_entry)
2778 local regularweight = regular_entry.pfmweight or 400
2779 local weight = entry.pfmweight
2780 if weight < regularweight + 100
2781 and (entry.subfamily == regular_entry.subfamily or style_synonym[entry.subfamily] ~= 'b') then
2782 return -- This font is not bold in any way
2783 end
2784 return 10000 * (entry.italicangle or 0)^2 -- We really don't want italic fonts here (italic font have an angle around 10)
2785 + .01 * ((entry.pfmweight or 400) - (regularweight + 200))^2 -- weights are normally multiples of 100, so they are still quite large after .01
2786 + ((entry.width or 5) - regular_entry.width)^2
2787 + (style_synonym[entry.subfamily or entry.typographicsubfamily] == 'b' and 0 or 1000000)
2788 + (entry.pfmweight > 500 and 0 or 10000)
2789 end
2790 local function bolditalic_score(entry, bold_entry, italic_entry)
2791 local italicangle = italic_entry.italicangle or 0
2792 local angle = entry.italicangle or 0
2793 local boldweight = bold_entry.pfmweight or 400
2794 local weight = entry.pfmweight or 400
2795 if (angle == 0 or weight < boldweight)
2796 and (entry.subfamily == bold_entry.subfamily or entry.subfamily == italic_entry.subfamily or style_synonym[entry.subfamily] ~= 'bi') then
2797 return -- This font is not italic in any way
2798 end
2799 return 100 * (angle - italicangle)^2
2800 + (weight - boldweight)^2
2801 + ((entry.width or 5) - bold_entry.width)^2
2802 + (style_synonym[entry.subfamily or entry.typographicsubfamily] == 'bi' and 0 or 1000000)
2803 end
2804
2805 local function pull_values (entry)
2806 local file = entry.file
2807 local names = entry.names
2808 local style = entry.style
2809 local sanitized = names.sanitized
2810 local english = sanitized.english
2811 local info = sanitized.info
2812 local metadata = sanitized.metadata
2813
2814 --- pull file info ...
2815 entry.basename = file.base
2816 entry.fullpath = file.full
2817 entry.location = file.location
2818 entry.subfont = file.subfont
2819
2820 --- pull name info ...
2821 entry.psname = english.psname
2822 entry.fontname = info.fontname or metadata.fontname
2823 entry.fullname = english.fullname or info.fullname
2824 entry.typographicsubfamily = english.typographicsubfamily
2825 entry.familyname = metadata.familyname or english.typographicfamily or english.family
2826 entry.plainname = names.fullname
2827 entry.subfamily = english.subfamily
2828
2829 --- pull style info ...
2830 entry.italicangle = style.italicangle
2831 entry.size = style.size
2832 entry.weight = style.weight
2833 entry.width = style.width
2834 entry.pfmweight = style.pfmweight
2835
2836 if config.luaotfload.db.strip == true then
2837 entry.file = nil
2838 entry.names = nil
2839 entry.style = nil
2840 end
2841 end
2842
2843 local function add_family (name, subtable, entry)
2844 if not name then --- probably borked font
2845 return
2846 end
2847 local familytable = subtable [name]
2848 if not familytable then
2849 familytable = { }
2850 subtable [name] = familytable
2851 end
2852
2853 familytable [#familytable + 1] = {
2854 index = entry.index,
2855 }
2856 end
2857
2858 local function get_subtable (families, entry)
2859 local location = entry.location
2860 local format = entry.format
2861 local subtable = families [location] [format]
2862 if not subtable then
2863 subtable = { }
2864 families [location] [format] = subtable
2865 end
2866 return subtable
2867 end
2868
2869 local function collect_families (mappings)
2870
2871 logreport ("info", 2, "db", "Analyzing families.")
2872
2873 local families = {
2874 ["local"] = { },
2875 system = { },
2876 texmf = { },
2877 }
2878
2879 for i = 1, #mappings do
2880
2881 local entry = mappings [i]
2882
2883 if entry.file then
2884 pull_values (entry)
2885 end
2886
2887 local subtable = get_subtable (families, entry)
2888 local familyname = entry.familyname
2889 local typographicsubfamily = entry.typographicsubfamily
2890 local subfamily = entry.subfamily
2891 local weight = entry.weight
2892 local width = entry.width
2893 local pfmweight = entry.pfmweight
2894 local italicangle = entry.italicangle
2895 add_family (familyname, subtable, entry)
2896 end
2897
2898 collectgarbage "collect"
2899 return families
2900 end
2901
2902 local function collect_fontnames (mappings)
2903
2904 logreport ("info", 2, "db", "Collecting fontnames.")
2905
2906 local fontnames = {
2907 ["local"] = { },
2908 system = { },
2909 texmf = { },
2910 }
2911
2912 for i = 1, #mappings do
2913 local entry = mappings [i]
2914
2915 local subtable = get_subtable (fontnames, entry)
2916 if entry.fontname then subtable[entry.fontname] = i end
2917 if entry.fullname then subtable[entry.fullname] = i end
2918 if entry.psname then subtable[entry.psname] = i end
2919 end
2920
2921 collectgarbage "collect"
2922 return fontnames
2923 end
2924
2925 --[[doc--
2926
2927 group_modifiers -- For not-quite-bold faces, determine whether
2928 they can fill in for a missing bold face slot in a matching family.
2929
2930 Some families like Lucida do not contain real bold / bold italic
2931 members. Instead, they have semibold variants at weight 600 which
2932 we must add in a separate pass.
2933
2934 --doc]]--
2935
2936 local style_categories = { "r", "b", "i", "bi" }
2937 local bold_categories = { "b", "bi" }
2938
2939 local huge = math.huge
2940 local function group_modifiers (mappings, families)
2941 logreport ("info", 2, "db", "Analyzing shapes, weights, and styles.")
2942 for location, location_data in next, families do
2943 for format, format_data in next, location_data do
2944 for familyname, collected in next, format_data do
2945 local best_score = huge
2946 local best_match
2947 for i=1,#collected do
2948 local v = collected[i]
2949 local entry = mappings[v.index]
2950 local score = regular_score(entry)
2951 if score <= best_score then
2952 v.prev = best_score == score and best_match or nil
2953 best_score = score
2954 best_match = v
2955 end
2956 end
2957 local regular = {}
2958 repeat
2959 local index = best_match.index
2960 local entry = mappings[index]
2961 local size = entry.size
2962 if size then
2963 regular [#regular + 1] = {
2964 size [1],
2965 size [2],
2966 size [3],
2967 index,
2968 }
2969 else
2970 regular.default = index
2971 end
2972 best_match = best_match.prev
2973 until not best_match
2974 local regular_entry = mappings[regular.default or regular[1][4]]
2975 local best_match_i, best_match_b
2976 local best_score_i, best_score_b = 10000000000, 10000000000
2977 for i=1,#collected do
2978 local v = collected[i]
2979 local entry = mappings[v.index]
2980 local score_i = italic_score(entry, regular_entry)
2981 local score_b = bold_score(entry, regular_entry)
2982 if score_i and score_i <= best_score_i then
2983 v.prev = best_score_i == score_i and best_match_i or nil
2984 best_score_i = score_i
2985 best_match_i = v
2986 end
2987 if score_b and score_b <= best_score_b then
2988 v.prev = best_score_b == score_b and best_match_b or nil
2989 best_score_b = score_b
2990 best_match_b = v
2991 end
2992 end
2993 local italic, bold
2994 if best_match_i then
2995 italic = {}
2996 repeat
2997 local index = best_match_i.index
2998 local entry = mappings[index]
2999 local size = entry.size
3000 if size then
3001 italic [#italic + 1] = {
3002 size [1],
3003 size [2],
3004 size [3],
3005 index,
3006 }
3007 else
3008 italic.default = index
3009 end
3010 best_match_i = best_match_i.prev
3011 until not best_match_i
3012 end
3013 if best_match_b then
3014 bold = {}
3015 repeat
3016 local index = best_match_b.index
3017 local entry = mappings[index]
3018 local size = entry.size
3019 if size then
3020 bold [#bold + 1] = {
3021 size [1],
3022 size [2],
3023 size [3],
3024 index,
3025 }
3026 else
3027 bold.default = index
3028 end
3029 best_match_b = best_match_b.prev
3030 until not best_match_b
3031 end
3032 local bolditalic
3033 if bold and italic then
3034 best_score = 1000000000000
3035 local bold_entry = mappings[bold.default or bold[1][4]]
3036 local italic_entry = mappings[italic.default or italic[1][4]]
3037 for i=1,#collected do
3038 local v = collected[i]
3039 local entry = mappings[v.index]
3040 local score = bolditalic_score(entry, bold_entry, italic_entry)
3041 if score and score <= best_score then
3042 v.prev = best_score == score and best_match or nil
3043 best_score = score
3044 best_match = v
3045 end
3046 end
3047 if best_match then
3048 bolditalic = {}
3049 repeat
3050 local index = best_match.index
3051 local entry = mappings[index]
3052 local size = entry.size
3053 if size then
3054 bolditalic [#bolditalic + 1] = {
3055 size [1],
3056 size [2],
3057 size [3],
3058 index,
3059 }
3060 else
3061 bolditalic.default = index
3062 end
3063 best_match = best_match.prev
3064 until not best_match
3065 end
3066 end
3067 format_data [familyname] = { r = regular, b = bold, i = italic, bi = bolditalic }
3068 end
3069 end
3070 end
3071 return families
3072 end
3073
3074 local function cmp_sizes (a, b)
3075 return a [1] < b [1]
3076 end
3077
3078 local function order_design_sizes (families)
3079
3080 logreport ("info", 2, "db", "Ordering design sizes.")
3081
3082 for location, data in next, families do
3083 for format, data in next, data do
3084 for familyname, data in next, data do
3085 for style, data in next, data do
3086 tablesort (data, cmp_sizes)
3087 end
3088 end
3089 end
3090 end
3091
3092 return families
3093 end
3094
3095 --[[doc--
3096
3097 Get the subfont index corresponding to a given psname in a
3098 font collection
3099
3100 --doc]]--
3101
3102 local function lookup_subfont_index(filepath, psname)
3103 assert(name_index)
3104 -- if not name_index then name_index = load_names () end
3105 local filestatus = name_index.status[filepath]
3106 local mappings = name_index.mappings
3107 if filestatus then
3108 for subfont, idx in next, filestatus.index do
3109 if mappings[idx].psname == psname then
3110 return subfont or 1
3111 end
3112 end
3113 end
3114
3115 -- If that didn't work, we do a manual search
3116 psname = sanitize_fontname(psname)
3117 local err, info = read_font_file (filepath)
3118 if #info == 0 then return 1 end
3119 for i = 1, #info do
3120 for _, names in next, info[i].platformnames do
3121 if psname == sanitize_fontname(names.postscriptname) then
3122 return i
3123 end
3124 end
3125 end
3126 end
3127
3128 --[[doc--
3129
3130 collect_font_filenames -- Scan the three search path categories for
3131 font files. This constitutes the first pass of the update mode.
3132
3133 --doc]]--
3134
3135 --- unit -> string * string list
3136 local function collect_font_filenames ()
3137
3138 logreport ("info", 4, "db", "Scanning the filesystem for font files.")
3139
3140 local filenames = { }
3141 local bisect = config.luaotfload.misc.bisect
3142 local max_fonts = config.luaotfload.db.max_fonts --- XXX revisit for lua 5.3 wrt integers
3143
3144 -- We can't just scan in the order of location_precedence here since
3145 -- the order is important. In the common situation of having texmf
3146 -- added to the system font path, scanning system first would
3147 -- classify all texmf fonts as system fonts.
3148 if enabled_locations.texmf then
3149 tableappend (filenames, collect_font_filenames_texmf ())
3150 end
3151 if enabled_locations.system then
3152 tableappend (filenames, collect_font_filenames_system ())
3153 end
3154 if enabled_locations['local'] then
3155 local localfonts, found = collect_font_filenames_local()
3156 if found then
3157 tableappend (filenames, localfonts)
3158 else
3159 scan_local = false
3160 end
3161 end
3162 --- Now drop everything above max_fonts.
3163 if max_fonts < #filenames then
3164 filenames = { unpack (filenames, 1, max_fonts) }
3165 end
3166 --- And choose the requested slice if in bisect mode.
3167 if bisect then
3168 return { unpack (filenames, bisect[1], bisect[2]) }
3169 end
3170 return filenames
3171 end
3172
3173 --[[doc--
3174
3175 nth_font_file -- Return the filename of the nth font.
3176
3177 --doc]]--
3178
3179 --- int -> string
3180 local function nth_font_filename (n)
3181 logreport ("info", 4, "db", "Picking font file no. %d.", n)
3182 if not p_blacklist then
3183 read_blacklist ()
3184 end
3185 local filenames = collect_font_filenames ()
3186 return filenames[n] and filenames[n][1] or "<error>"
3187 end
3188
3189 --[[doc--
3190
3191 font_slice -- Return the fonts in the range from lo to hi.
3192
3193 --doc]]--
3194
3195 local function font_slice (lo, hi)
3196 logreport ("info", 4, "db", "Retrieving font files nos. %d--%d.", lo, hi)
3197 if not p_blacklist then
3198 read_blacklist ()
3199 end
3200 local filenames = collect_font_filenames ()
3201 local result = { }
3202 for i = lo, hi do
3203 result[#result + 1] = filenames[i][1]
3204 end
3205 return result
3206 end
3207
3208 --[[doc
3209
3210 count_font_files -- Return the number of files found by
3211 collect_font_filenames. This function is exported primarily
3212 for use with luaotfload-tool.lua in bisect mode.
3213
3214 --doc]]--
3215
3216 --- unit -> int
3217 local function count_font_files ()
3218 logreport ("info", 4, "db", "Counting font files.")
3219 if not p_blacklist then
3220 read_blacklist ()
3221 end
3222 return #collect_font_filenames ()
3223 end
3224
3225 --- dbobj -> stats
3226
3227 local function collect_statistics (mappings)
3228 local sum_dsnsize, n_dsnsize = 0, 0
3229
3230 local fullname, family, families = { }, { }, { }
3231 local subfamily, typographicsubfamily = { }, { }
3232
3233 local function addtohash (hash, item)
3234 if item then
3235 local times = hash [item]
3236 if times then
3237 hash [item] = times + 1
3238 else
3239 hash [item] = 1
3240 end
3241 end
3242 end
3243
3244 local function appendtohash (hash, key, value)
3245 if key and value then
3246 local entry = hash [key]
3247 if entry then
3248 entry [#entry + 1] = value
3249 else
3250 hash [key] = { value }
3251 end
3252 end
3253 end
3254
3255 local function addtoset (hash, key, value)
3256 if key and value then
3257 local set = hash [key]
3258 if set then
3259 set [value] = true
3260 else
3261 hash [key] = { [value] = true }
3262 end
3263 end
3264 end
3265
3266 local function setsize (set)
3267 local n = 0
3268 for _, _ in next, set do
3269 n = n + 1
3270 end
3271 return n
3272 end
3273
3274 local function hashsum (hash)
3275 local n = 0
3276 for _, m in next, hash do
3277 n = n + m
3278 end
3279 return n
3280 end
3281
3282 for _, entry in next, mappings do
3283 local style = entry.style
3284 local names = entry.names.sanitized
3285 local englishnames = names.english
3286
3287 addtohash (fullname, englishnames.fullname)
3288 addtohash (family, englishnames.family)
3289 addtohash (subfamily, englishnames.subfamily)
3290 addtohash (typographicsubfamily, englishnames.typographicsubfamily)
3291
3292 addtoset (families, englishnames.family, englishnames.fullname)
3293
3294 local sizeinfo = entry.style.size
3295 if sizeinfo then
3296 sum_dsnsize = sum_dsnsize + sizeinfo [1]
3297 n_dsnsize = n_dsnsize + 1
3298 end
3299 end
3300
3301 --inspect (families)
3302
3303 local n_fullname = setsize (fullname)
3304 local n_family = setsize (family)
3305
3306 if log.get_loglevel () > 1 then
3307 local function pprint_top (hash, n, set)
3308
3309 local freqs = { }
3310 local items = { }
3311
3312 for item, value in next, hash do
3313 if set then
3314 freq = setsize (value)
3315 else
3316 freq = value
3317 end
3318 local ifreq = items [freq]
3319 if ifreq then
3320 ifreq [#ifreq + 1] = item
3321 else
3322 items [freq] = { item }
3323 freqs [#freqs + 1] = freq
3324 end
3325 end
3326
3327 tablesort (freqs)
3328
3329 local from = #freqs
3330 local to = from - (n - 1)
3331 if to < 1 then
3332 to = 1
3333 end
3334
3335 for i = from, to, -1 do
3336 local freq = freqs [i]
3337 local itemlist = items [freq]
3338
3339 if type (itemlist) == "table" then
3340 itemlist = tableconcat (itemlist, ", ")
3341 end
3342
3343 logreport ("both", 0, "db",
3344 " · %4d × %s.",
3345 freq, itemlist)
3346 end
3347 end
3348
3349 logreport ("both", 0, "", "~~~~ font index statistics ~~~~")
3350 logreport ("both", 0, "db",
3351 " · Collected %d fonts (%d names) in %d families.",
3352 #mappings, n_fullname, n_family)
3353 pprint_top (families, 4, true)
3354
3355 logreport ("both", 0, "db",
3356 " · %d different \"subfamily\" kinds.",
3357 setsize (subfamily))
3358 pprint_top (subfamily, 4)
3359
3360 logreport ("both", 0, "db",
3361 " · %d different \"typographicsubfamily\" kinds.",
3362 setsize (typographicsubfamily))
3363 pprint_top (typographicsubfamily, 4)
3364
3365 end
3366
3367 local mean_dsnsize = 0
3368 if n_dsnsize > 0 then
3369 mean_dsnsize = sum_dsnsize / n_dsnsize
3370 end
3371
3372 return {
3373 mean_dsnsize = mean_dsnsize,
3374 names = {
3375 fullname = n_fullname,
3376 families = n_family,
3377 },
3378 -- style = {
3379 -- subfamily = subfamily,
3380 -- typographicsubfamily = typographicsubfamily,
3381 -- },
3382 }
3383 end
3384
3385 --- force: dictate rebuild from scratch
3386 --- dry_dun: don’t write to the db, just scan dirs
3387
3388 --- dbobj? -> bool? -> bool? -> dbobj
3389 function update_names (currentnames, force, dry_run)
3390 local targetnames
3391 local n_new = 0
3392 local n_rem = 0
3393
3394 local conf = config.luaotfload
3395 if conf.run.live ~= false and conf.db.update_live == false then
3396 logreport ("info", 2, "db", "Skipping database update.")
3397 --- skip all db updates
3398 return currentnames or name_index
3399 end
3400
3401 local starttime = osgettimeofday ()
3402
3403 --[[
3404 The main function, scans everything
3405 - “targetnames” is the final table to return
3406 - force is whether we rebuild it from scratch or not
3407 ]]
3408 logreport ("both", 1, "db",
3409 "Updating the font names database"
3410 .. (force and " forcefully." or "."))
3411
3412 if config.luaotfload.db.skip_read == true then
3413 --- the difference to a “dry run” is that we don’t search
3414 --- for font files entirely. we also ignore the “force”
3415 --- parameter since it concerns only the font files.
3416 logreport ("info", 2, "db",
3417 "Ignoring font files, reusing old data.")
3418 currentnames = load_names (false)
3419 targetnames = currentnames
3420 else
3421 if force then
3422 currentnames = initialize_namedata (get_font_filter ())
3423 else
3424 if not currentnames or not next (currentnames) then
3425 currentnames = load_names (dry_run)
3426 end
3427 if currentnames.meta.version ~= names.version then
3428 logreport ("both", 1, "db",
3429 "No font names database or old \z
3430 one found; generating new one.")
3431 currentnames = initialize_namedata (get_font_filter ())
3432 end
3433 end
3434
3435 targetnames = initialize_namedata (get_font_filter (),
3436 currentnames.meta and currentnames.meta.created)
3437
3438 read_blacklist ()
3439
3440 --- pass 1: Collect the names of all fonts we are going to process.
3441 local font_filenames = collect_font_filenames ()
3442 if enabled_locations['local'] then
3443 targetnames.meta['local'] = true
3444 end
3445
3446 --- pass 2: read font files (normal case) or reuse information
3447 --- present in index
3448
3449 n_rem = count_removed (currentnames.files)
3450
3451 n_new = retrieve_namedata (font_filenames,
3452 currentnames,
3453 targetnames,
3454 dry_run)
3455
3456 logreport ("info", 3, "db",
3457 "Found %d font files; %d new, %d stale entries.",
3458 #font_filenames, n_new, n_rem)
3459 end
3460
3461 --- pass 3 (optional): collect some stats about the raw font info
3462 if config.luaotfload.misc.statistics == true then
3463 targetnames.meta.statistics = collect_statistics
3464 (targetnames.mappings)
3465 end
3466
3467 --- we always generate the file lookup tables because
3468 --- non-texmf entries are redirected there and the mapping
3469 --- needs to be 100% consistent
3470
3471 --- pass 4: build filename table
3472 targetnames.files = generate_filedata (targetnames.mappings)
3473
3474 --- pass 5: build family lookup table
3475 targetnames.families = collect_families (targetnames.mappings)
3476
3477 --- pass 6: arrange style and size info
3478 targetnames.families = group_modifiers (targetnames.mappings,
3479 targetnames.families)
3480 --- pass 7: order design size tables
3481 targetnames.families = order_design_sizes (targetnames.families)
3482
3483 --- pass 8: build family lookup table
3484 targetnames.fontnames = collect_fontnames (targetnames.mappings)
3485
3486 logreport ("info", 3, "db",
3487 "Rebuilt in %0.f ms.",
3488 1000 * (osgettimeofday () - starttime))
3489 name_index = targetnames
3490
3491 if dry_run ~= true then
3492
3493 if n_new + n_rem == 0 then
3494 logreport ("info", 2, "db",
3495 "No new or removed fonts, skip saving to disk.")
3496 else
3497 local success, reason = save_names ()
3498 if not success then
3499 logreport ("both", 0, "db",
3500 "Failed to save database to disk: %s",
3501 reason)
3502 end
3503 end
3504
3505 if flush_lookup_cache () and save_lookups () then
3506 logreport ("both", 2, "cache", "Lookup cache emptied.")
3507 return targetnames
3508 end
3509 end
3510 return targetnames
3511 end
3512
3513 local function compress_dummy(data) return data end
3514 --- string -> string -> (string * table)
3515 local function save_lua_table (data, path_lua, path_luc, compress)
3516 if compress then
3517 osremove(path_lua)
3518 osremove(path_luc)
3519 path_lua, path_luc = path_lua .. '.gz', path_luc .. '.gz'
3520 else
3521 osremove(path_lua .. '.gz')
3522 osremove(path_luc .. '.gz')
3523 end
3524 local file_lua, msg = ioopen(path_lua, compress and 'wb' or 'w')
3525 if not file_lua then
3526 logreport ("info", 0, "cache", "Failed to write %q: %s", path_lua, msg)
3527 end
3528 local file_luc file_luc, msg = ioopen(path_luc, 'wb')
3529 if not file_luc then
3530 logreport ("info", 0, "cache", "Failed to write %q: %s", path_luc, msg)
3531 end
3532 if not (file_lua or file_luc) then
3533 return
3534 end
3535 -- If we can only write one of the files, try to remove the other
3536 -- one to avoid them beiing inconsistent. This will probably fail,
3537 -- but in some situations we might be allowed to delete a file we
3538 -- can't write to.
3539 if not file_lua then
3540 osremove(path_lua)
3541 elseif not file_luc then
3542 osremove(path_luc)
3543 end
3544 local serialized = tableserialize (data, true)
3545 if file_lua then
3546 file_lua:write(compress and gzip.compress(serialized, 31) or serialized)
3547 file_lua:close()
3548 end
3549 if file_luc then
3550 local compiled = dump(assert(load(serialized, 't')), true)
3551 file_luc:write(compress and gzip.compress(compiled, 31) or compiled)
3552 file_luc:close()
3553 end
3554 -- Even if we could write one file but not the other one it's still an
3555 -- error since reloading is then unreliable.
3556 return file_lua and path_lua or nil, file_luc and path_luc or nil
3557 end
3558
3559 --- unit -> bool
3560 function save_lookups ( )
3561 local paths = config.luaotfload.paths
3562 local luaname, lucname = paths.lookup_path_lua, paths.lookup_path_luc
3563 luaname, lucname = save_lua_table(lookup_cache, luaname, lucname)
3564 if luaname and lucname then
3565 logreport ("both", 3, "cache", "Lookup cache saved.")
3566 return true
3567 else
3568 logreport ("info", 0, "cache", "Lookup cache file not writable.")
3569 end
3570 return false
3571 end
3572
3573 --- save_names() is usually called without the argument
3574 --- dbobj? -> bool * string option
3575 function save_names (currentnames)
3576 if not currentnames then
3577 currentnames = name_index
3578 end
3579 if not currentnames or type (currentnames) ~= "table" then
3580 return false, "invalid names table"
3581 elseif currentnames.meta and currentnames.meta["local"] then
3582 return false, "table contains local entries"
3583 end
3584 local paths = config.luaotfload.paths
3585 local luaname, lucname = paths.index_path_lua, paths.index_path_luc
3586 local compress = config.luaotfload.db.compress
3587 luaname, lucname = save_lua_table(currentnames, luaname, lucname, compress)
3588 if luaname and lucname then
3589 logreport ("info", 2, "db", "Font index saved at ...")
3590 logreport ("info", 2, "db", "Text: " .. luaname)
3591 logreport ("info", 2, "db", "Byte: " .. lucname)
3592 return true
3593 end
3594 logreport ("info", 0, "db", "Index file not writable")
3595 return false
3596 end
3597
3598 --[[doc--
3599
3600 Below set of functions is modeled after mtx-cache.
3601
3602 --doc]]--
3603
3604 --- string -> string -> string list -> string list -> string list -> unit
3605 local function print_cache (category, path, luanames, lucnames, rest)
3606 local function report_indeed (...)
3607 logreport ("info", 0, "cache", ...)
3608 end
3609 report_indeed("Luaotfload cache: %s", category)
3610 report_indeed("location: %s", path)
3611 report_indeed("[raw] %4i", #luanames)
3612 report_indeed("[compiled] %4i", #lucnames)
3613 report_indeed("[other] %4i", #rest)
3614 report_indeed("[total] %4i", #luanames + #lucnames + #rest)
3615 end
3616
3617 --- string -> string -> string list -> bool -> bool
3618 local function purge_from_cache (category, path, list, all)
3619 logreport ("info", 1, "cache", "Luaotfload cache: %s %s",
3620 (all and "erase" or "purge"), category)
3621 logreport ("info", 1, "cache", "location: %s", path)
3622 local n = 0
3623 for i=1,#list do
3624 local filename = list[i]
3625 if stringfind(filename,"luatex%-cache") then -- safeguard
3626 if all then
3627 logreport ("info", 5, "cache", "Removing %s.", filename)
3628 osremove(filename)
3629 n = n + 1
3630 else
3631 local suffix = filesuffix(filename)
3632 if suffix == "lua" then
3633 local checkname = file.replacesuffix(
3634 filename, "lua", "luc")
3635 if lfsisfile(checkname) then
3636 logreport ("info", 5, "cache", "Removing %s.", filename)
3637 osremove(filename)
3638 n = n + 1
3639 end
3640 end
3641 end
3642 end
3643 end
3644 logreport ("info", 1, "cache", "Removed lua files : %i", n)
3645 return true
3646 end
3647
3648 --- string -> string list -> int -> string list -> string list -> string list ->
3649 --- (string list * string list * string list * string list)
3650 local function collect_cache (path, all, n, luanames, lucnames, rest)
3651 if not all then
3652 local all = find_files (path)
3653
3654 local luanames, lucnames, rest = { }, { }, { }
3655 return collect_cache(nil, all, 1, luanames, lucnames, rest)
3656 end
3657
3658 local filename = all[n]
3659 if filename then
3660 local suffix = filesuffix(filename)
3661 if suffix == "lua" then
3662 luanames[#luanames+1] = filename
3663 elseif suffix == "luc" then
3664 lucnames[#lucnames+1] = filename
3665 else
3666 rest[#rest+1] = filename
3667 end
3668 return collect_cache(nil, all, n+1, luanames, lucnames, rest)
3669 end
3670 return luanames, lucnames, rest, all
3671 end
3672
3673 local function getwritablecachepath ( )
3674 --- fonts.handlers.otf doesn’t exist outside a Luatex run,
3675 --- so we have to improvise
3676 local writable = getwritablepath (config.luaotfload.paths.cache_dir, "")
3677 if writable then
3678 return writable
3679 end
3680 end
3681
3682 local function getreadablecachepaths ( )
3683 local readables = caches.getreadablepaths
3684 (config.luaotfload.paths.cache_dir)
3685 local result = { }
3686 if readables then
3687 for i=1, #readables do
3688 local readable = readables[i]
3689 if lfsisdir (readable) then
3690 result[#result+1] = readable
3691 end
3692 end
3693 end
3694 return result
3695 end
3696
3697 --- unit -> unit
3698 local function purge_cache ( )
3699 local writable_path = getwritablecachepath ()
3700 local luanames, lucnames, rest = collect_cache(writable_path)
3701 if log.get_loglevel() > 1 then
3702 print_cache("writable path", writable_path, luanames, lucnames, rest)
3703 end
3704 local success = purge_from_cache("writable path", writable_path, luanames, false)
3705 return success
3706 end
3707
3708 --- unit -> unit
3709 local function erase_cache ( )
3710 local writable_path = getwritablecachepath ()
3711 local luanames, lucnames, rest, all = collect_cache(writable_path)
3712 if log.get_loglevel() > 1 then
3713 print_cache("writable path", writable_path, luanames, lucnames, rest)
3714 end
3715 local success = purge_from_cache("writable path", writable_path, all, true)
3716 return success
3717 end
3718
3719 local function separator ( )
3720 logreport ("info", 0, string.rep("-", 67))
3721 end
3722
3723 --- unit -> unit
3724 local function show_cache ( )
3725 local readable_paths = getreadablecachepaths ()
3726 local writable_path = getwritablecachepath ()
3727 local luanames, lucnames, rest = collect_cache(writable_path)
3728
3729 separator ()
3730 print_cache ("writable path", writable_path,
3731 luanames, lucnames, rest)
3732 texio.write_nl""
3733 for i=1,#readable_paths do
3734 local readable_path = readable_paths[i]
3735 if readable_path ~= writable_path then
3736 local luanames, lucnames = collect_cache (readable_path)
3737 print_cache ("readable path",
3738 readable_path, luanames, lucnames, rest)
3739 end
3740 end
3741 separator()
3742 return true
3743 end
3744
3745 -----------------------------------------------------------------------
3746 --- API assumptions of the fontloader
3747 -----------------------------------------------------------------------
3748 --- PHG: we need to investigate these, maybe they’re useful as early
3749 --- hooks
3750
3751 local function reportmissingbase ()
3752 logreport ("info", 0, "db", --> bug‽
3753 "Font name database not found but expected by fontloader.")
3754 fonts.names.reportmissingbase = nil
3755 end
3756
3757 local function reportmissingname ()
3758 logreport ("info", 0, "db", --> bug‽
3759 "Fontloader attempted to lookup name before Luaotfload \z
3760 was initialized.")
3761 fonts.names.reportmissingname = nil
3762 end
3763
3764 local function getfilename (a1, a2)
3765 logreport ("info", 6, "db", --> bug‽
3766 "Fontloader looked up font file (%s, %s) before Luaotfload \z
3767 was initialized.", tostring(a1), tostring(a2))
3768 return lookup_fullpath (a1, a2)
3769 end
3770
3771 local function resolve (name, subfont)
3772 logreport ("info", 6, "db", --> bug‽
3773 "Fontloader attempted to resolve name (%s, %s) before \z
3774 Luaotfload was initialized.", tostring(name), tostring(subfont))
3775 return lookup_font_name { name = name, sub = subfont }
3776 end
3777
3778 local api = {
3779 ignoredfile = function() return false end,
3780 reportmissingbase = reportmissingbase,
3781 reportmissingname = reportmissingname,
3782 getfilename = getfilename,
3783 resolve = resolve,
3784 }
3785
3786 -----------------------------------------------------------------------
3787 --- export functionality to the namespace “fonts.names”
3788 -----------------------------------------------------------------------
3789
3790 local export = {
3791 set_font_filter = set_font_filter,
3792 set_size_dimension = set_size_dimension,
3793 flush_lookup_cache = flush_lookup_cache,
3794 save_lookups = save_lookups,
3795 load = load_names,
3796 access_font_index = access_font_index,
3797 data = function () return name_index end,
3798 save = save_names,
3799 update = update_names,
3800 lookup_font_file = lookup_font_file,
3801 lookup_font_name = lookup_font_name,
3802 lookup_font_name_cached = lookup_font_name_cached,
3803 getfilename = lookup_fullpath,
3804 lookup_fullpath = lookup_fullpath,
3805 read_blacklist = read_blacklist,
3806 sanitize_fontname = sanitize_fontname,
3807 getmetadata = getmetadata,
3808 set_location_precedence = set_location_precedence,
3809 count_font_files = count_font_files,
3810 nth_font_filename = nth_font_filename,
3811 font_slice = font_slice,
3812 lookup_subfont_index = lookup_subfont_index,
3813 --- font cache
3814 purge_cache = purge_cache,
3815 erase_cache = erase_cache,
3816 show_cache = show_cache,
3817 find_closest = find_closest,
3818 }
3819
3820 return function ()
3821 --- the font loader namespace is “fonts”, same as in Context
3822 --- we need to put some fallbacks into place for when running
3823 --- as a script
3824 if not fonts then return false end
3825 logreport = luaotfload.log.report
3826 local fonts = fonts
3827 fonts.names = fonts.names or names
3828 fonts.formats = fonts.formats or { }
3829 fonts.definers = fonts.definers or { resolvers = { } }
3830
3831 names.blacklist = blacklist
3832 names.version = 6 --- increase monotonically
3833 names.data = nil --- contains the loaded database
3834 names.lookups = nil --- contains the lookup cache
3835
3836 enabled_locations['local'] = enabled_locations['local'] and config.luaotfload.db.scan_local == true
3837 for sym, ref in next, export do names[sym] = ref end
3838 for sym, ref in next, api do names[sym] = names[sym] or ref end
3839 return true
3840 end
3841
3842 -- vim:tw=71:sw=4:ts=4:expandtab