OSDN Git Service

879d0b85b73ea910e78e805ed9d42c66e604720b
[luatex-ja/luatexja.git] / src / ltj-jfont.lua
1 --
2 -- luatexja/jfont.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfont',
6   date = '2016/03/31',
7   description = 'Loader for Japanese fonts',
8 })
9 module('luatexja.jfont', package.seeall)
10
11 luatexja.load_module('base');      local ltjb = luatexja.base
12 luatexja.load_module('charrange'); local ltjc = luatexja.charrange
13 luatexja.load_module('rmlgbm');    local ltjr = luatexja.rmlgbm
14 luatexja.load_module('direction'); local ltjd = luatexja.direction
15
16
17 local Dnode = node.direct or node
18
19 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
20 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
21
22 local nullfunc = function(n) return n end
23 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
24
25 local node_new = Dnode.new
26 local node_free = Dnode.free
27 local has_attr = Dnode.has_attribute
28 local set_attr = Dnode.set_attribute
29 local round = tex.round
30 local font_getfont = font.getfont
31
32 local attr_icflag = luatexbase.attributes['ltj@icflag']
33 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
34 local attr_curtfnt = luatexbase.attributes['ltj@curtfnt']
35 local id_glyph = node.id('glyph')
36 local id_kern = node.id('kern')
37 local id_glue_spec = node.id('glue_spec')
38 local id_glue = node.id('glue')
39 local cat_lp = luatexbase.catcodetables['latex-package']
40 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
41 local tokenlib = luatexja.token
42 ------------------------------------------------------------------------
43 -- LOADING JFM
44 ------------------------------------------------------------------------
45
46 metrics={} -- this table stores all metric informations
47 font_metric_table={} -- [font number] -> jfm_name, jfm_var, size
48
49 luatexbase.create_callback("luatexja.load_jfm", "data", function (ft, jn) return ft end)
50
51 local jfm_file_name, jfm_var, jfm_ksp
52 local defjfm_res
53 local jfm_dir, is_def_jfont, is_vert_enabled
54
55 local function norm_val(a)
56    if (not a) or (a==0.) then
57       return nil
58    elseif a==true then
59       return 1
60    else
61       return a
62    end
63 end
64
65 function define_jfm(t)
66    local real_char -- Does current character class have the 'real' character?
67    if t.dir~=jfm_dir then
68       defjfm_res= nil; return
69    elseif type(t.zw)~='number' or type(t.zh)~='number' then
70       defjfm_res= nil; return
71    end
72    t.char_type = {}; t.chars = {}
73    for i,v in pairs(t) do
74       if type(i) == 'number' then -- char_type
75          if not v.chars then
76             if i ~= 0 then defjfm_res= nil; return  end
77          else
78             for j,w in pairs(v.chars) do
79                if type(w) == 'number' and w~=-1 then
80                elseif type(w) == 'string' and utf.len(w)==1 then
81                   w = utf.byte(w)
82                elseif type(w) == 'string' and utf.len(w)==2 and utf.sub(w,2) == '*' then
83                   w = utf.byte(utf.sub(w,1,1))
84                end
85                if not t.chars[w] then
86                   t.chars[w] = i
87                else
88                   defjfm_res= nil; return
89                end
90             end
91             v.chars = nil
92          end
93          if type(v.align)~='string' then
94             v.align = 'left' -- left
95          end
96          if type(v.width)~='number' then
97             v.width = (jfm_dir=='tate') and  1.0
98          end
99          if type(v.height)~='number' then
100             v.height = (jfm_dir=='tate') and  0.0
101          end
102          if type(v.depth)~='number' then
103             v.depth =  (jfm_dir=='tate') and  0.0
104          end
105          if type(v.italic)~='number' then
106             v.italic = 0.0
107          end
108          if type(v.left)~='number' then
109             v.left = 0.0
110          end
111          if type(v.down)~='number' then
112             v.down = 0.0
113          end
114          v.kern = v.kern or {}; v.glue = v.glue or {}
115          for j,x in pairs(v.glue) do
116             if v.kern[j] then defjfm_res= nil; return end
117             x.ratio, x[5] = (x.ratio or (x[5] and 0.5*(1+x[5]) or 0.5)), nil
118             x.priority, x[4] = (x.priority or x[4] or 0), nil
119             x.kanjiskip_natural = norm_val(x.kanjiskip_natural)
120             x.kanjiskip_stretch = norm_val(x.kanjiskip_stretch)
121             x.kanjiskip_shrink = norm_val(x.kanjiskip_shrink)
122          end
123          for j,x in pairs(v.kern) do
124             if type(x)=='number' then
125                v.kern[j] = {x, 0.5}
126             elseif type(x)=='table' then
127                v.kern[j] = { x[1], ratio=x.ratio or (x[2] and 0.5*(1+x[2]) or 0.5) }
128             end
129          end
130          t.char_type[i] = v
131          t[i] = nil
132       end
133    end
134    t = luatexbase.call_callback("luatexja.load_jfm", t, jfm_file_name)
135    t.size_cache = {}
136    defjfm_res = t
137 end
138
139 local update_jfm_cache
140 do
141    local function mult_table(old,scale) -- modified from table.fastcopy
142       if old then
143          local new = { }
144          for k,v in next, old do
145             if type(v) == "table" then
146                new[k] = mult_table(v,scale)
147             elseif type(v) == "number" then
148                new[k] = round(v*scale)
149             else
150                new[k] = v
151             end
152          end
153          return new
154       else return nil end
155    end
156    update_jfm_cache = function (j,sz)
157       if metrics[j].size_cache[sz] then return end
158       --local TEMP = node_new(id_kern)
159       local t = {}
160       metrics[j].size_cache[sz] = t
161       t.chars = metrics[j].chars
162       t.char_type = mult_table(metrics[j].char_type, sz)
163       for i,v in pairs(t.char_type) do
164          v.align = (v.align=='left') and 0 or
165             ((v.align=='right') and 1 or 0.5)
166          if type(i) == 'number' then -- char_type
167             for k,w in pairs(v.glue) do
168                local h = node_new(id_glue_spec)
169                v[k] = {
170                   true, h,
171                   ratio=w.ratio/sz,
172                   priority=FROM_JFM + w.priority/sz,
173                   kanjiskip_natural = w.kanjiskip_natural and w.kanjiskip_natural/sz,
174                   kanjiskip_stretch = w.kanjiskip_stretch and w.kanjiskip_stretch/sz,
175                   kanjiskip_shrink =  w.kanjiskip_shrink  and w.kanjiskip_shrink/sz,
176                }
177                setfield(h, 'width', w[1])
178                setfield(h, 'stretch', w[2])
179                setfield(h, 'shrink', w[3])
180                setfield(h, 'stretch_order', 0)
181                setfield(h, 'shrink_order', 0)
182             end
183             for k,w in pairs(v.kern) do
184                local g = node_new(id_kern)
185                setfield(g, 'kern', w[1])
186                setfield(g, 'subtype', 1)
187                set_attr(g, attr_icflag, FROM_JFM)
188                v[k] = {false, g, ratio=w[2]/sz}
189             end
190          end
191          v.glue, v.kern = nil, nil
192       end
193       t.kanjiskip = mult_table(metrics[j].kanjiskip, sz)
194       t.xkanjiskip = mult_table(metrics[j].xkanjiskip,sz)
195       t.zw = round(metrics[j].zw*sz)
196       t.zh = round(metrics[j].zh*sz)
197       t.size = sz
198       --node_free(TEMP)
199    end
200 end
201
202 luatexbase.create_callback("luatexja.find_char_class", "data",
203                            function (arg, fmtable, char)
204                               return 0
205                            end)
206 do
207    local start_time_measure = ltjb.start_time_measure
208    local stop_time_measure = ltjb.stop_time_measure
209    local fcc_temp = { chars_cbcache = {} }
210    setmetatable(
211       fcc_temp.chars_cbcache,
212       {
213          __index = function () return 0 end,
214       })
215    function find_char_class(c,m)
216       -- c: character code, m:
217       local r = (m or fcc_temp).chars_cbcache[c]
218       if not r then
219          r = m.chars[c] or
220             luatexbase.call_callback("luatexja.find_char_class", 0, m, c)
221          m.chars_cbcache[c or 0] = r
222       end
223       return r
224    end
225 end
226
227
228 ------------------------------------------------------------------------
229 -- LOADING JAPANESE FONTS
230 ------------------------------------------------------------------------
231
232 do
233    local cstemp
234    local global_flag -- true if \globaljfont, false if \jfont
235    local function load_jfont_metric()
236       if jfm_file_name=='' then
237          ltjb.package_error('luatexja',
238                             'no JFM specified',
239                             'To load and define a Japanese font, a JFM must be specified.'..
240                             "The JFM 'ujis' will be  used for now.")
241          jfm_file_name='ujis'
242       end
243       for j,v in ipairs(metrics) do
244          if v.name==jfm_file_name then return j end
245       end
246       luatexja.load_lua('jfm-' .. jfm_file_name .. '.lua')
247       if defjfm_res then
248          defjfm_res.name = jfm_file_name
249          table.insert(metrics, defjfm_res)
250          return #metrics
251       else
252          return nil
253       end
254    end
255
256 -- EXT
257    local utf8 = unicode.utf8
258    function jfontdefX(g, dir, csname)
259       jfm_dir, is_def_jfont = dir, true
260       cstemp = csname:sub( (utf8.byte(csname,1,1) == tex.escapechar) and 2 or 1, -1)
261       cstemp = cstemp:sub(1, ((cstemp:sub(-1,-1)==' ') and (cstemp:len()>=2)) and -2 or -1)
262       global_flag = g and '\\global' or ''
263       tex.sprint(cat_lp, '\\expandafter\\font\\csname ',
264                  (cstemp==' ') and '\\space' or cstemp, '\\endcsname')
265    end
266
267    luatexbase.create_callback("luatexja.define_jfont", "data", function (ft, fn) return ft end)
268
269 -- EXT
270    local identifiers = fonts.hashes.identifiers
271    function jfontdefY()
272       local j = load_jfont_metric(jfm_dir)
273       local fn = font.id(cstemp)
274       local f = font_getfont(fn)
275       if not j then
276          ltjb.package_error('luatexja',
277                             "bad JFM `" .. jfm_file_name .. "'",
278                             'The JFM file you specified is not valid JFM file.\n'..
279                                'So defining Japanese font is cancelled.')
280          tex.sprint(cat_lp, global_flag, '\\expandafter\\let\\csname ',
281                     (cstemp==' ') and '\\space' or cstemp,
282                        '\\endcsname=\\relax')
283          return
284       end
285       update_jfm_cache(j, f.size)
286       local ad = identifiers[fn].parameters
287       local sz = metrics[j].size_cache[f.size]
288       local fmtable = { jfm = j, size = f.size, var = jfm_var,
289                         with_kanjiskip = jfm_ksp,
290                         zw = sz.zw, zh = sz.zh,
291                         ascent = ad.ascender,
292                         descent = ad.descender,
293                         chars = sz.chars, char_type = sz.char_type,
294                         kanjiskip = sz.kanjiskip, xkanjiskip = sz.xkanjiskip,
295                         chars_cbcache = {},
296                         vert_activated = is_vert_enabled,
297       }
298
299       fmtable = luatexbase.call_callback("luatexja.define_jfont", fmtable, fn)
300       font_metric_table[fn]=fmtable
301       tex.sprint(cat_lp, global_flag, '\\protected\\expandafter\\def\\csname ',
302                     (cstemp==' ') and '\\space' or cstemp, '\\endcsname{\\ltj@cur'..
303                     (jfm_dir == 'yoko' and 'j' or 't') .. 'fnt', fn, '\\relax}')
304    end
305 end
306
307 do
308    local get_dir_count = ltjd.get_dir_count
309    local dir_tate = luatexja.dir_table.dir_tate
310    local tex_get_attr = tex.getattribute
311    -- PUBLIC function
312    function get_zw()
313       local a = font_metric_table[
314          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
315       return a and a.zw or 0
316    end
317    function get_zh()
318       local a = font_metric_table[
319          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
320       return a and a.zw or 0
321    end
322 end
323
324 do
325    -- extract jfm_file_name and jfm_var
326    -- normalize position of 'jfm=' and 'jfmvar=' keys
327    local function extract_metric(name)
328       local is_braced = name:match('^{(.*)}$')
329        name= is_braced or name
330       jfm_file_name = ''; jfm_var = ''; jfm_ksp = true
331       local tmp, index = name:sub(1, 5), 1
332       if tmp == 'file:' or tmp == 'name:' or tmp == 'psft:' then
333          index = 6
334       end
335       local p = name:find(":", index); index = p and (p+1) or index
336       while index do
337          local l = name:len()+1
338          local q = name:find(";", index+1) or l
339          if name:sub(index, index+3)=='jfm=' and q>index+4 then
340             jfm_file_name = name:sub(index+4, q-1)
341             if l~=q then
342                name = name:sub(1,index-1) .. name:sub(q+1)
343             else
344                name = name:sub(1,index-1)
345                index = nil
346             end
347          elseif name:sub(index, index+6)=='jfmvar=' and q>index+6 then
348             jfm_var = name:sub(index+7, q-1)
349             if l~=q then
350                name = name:sub(1,index-1) .. name:sub(q+1)
351             else
352                name = name:sub(1,index-1)
353                index = nil
354             end
355          else
356             index = (l~=q) and (q+1) or nil
357          end
358       end
359       if jfm_file_name~='' then
360          local l = name:sub(-1)
361          name = name
362             .. ((l==':' or l==';') and '' or ';')
363             .. 'jfm=' .. jfm_file_name
364          if jfm_var~='' then
365             name = name .. 'jfmvar=' .. jfm_var
366          end
367       end
368       for x in string.gmatch (name, "[:;]([+%%-]?)ltjks") do
369          jfm_ksp = not (x=='-')
370       end
371       if jfm_dir == 'tate' then
372          is_vert_enabled = (not name:match('[:;]%-vert')) and (not  name:match('[:;]%-vrt2'))
373          if not name:match('vert') and not name:match('vrt2') then
374             name = name .. ';+vert;+vrt2'
375          end
376       else
377          is_vert_enabled = nil
378       end
379       return is_braced and ('{' .. name .. '}') or name
380    end
381
382    -- define_font callback
383    local otfl_fdr = fonts.definers.read
384    local ltjr_font_callback = ltjr.font_callback
385    function luatexja.font_callback(name, size, id)
386       local new_name = is_def_jfont and extract_metric(name) or name
387       is_def_jfont = false
388       --local res =  otfl_fdr(new_name, size, id)
389       local res =  ltjr_font_callback(new_name, size, id, otfl_fdr)
390       luatexbase.call_callback('luatexja.define_font', res, new_name, size, id)
391       -- this callback processes variation selector, so we execute it always
392       return res
393    end
394    luatexbase.create_callback('luatexja.define_font', 'simple', function (n) return n end)
395    luatexbase.add_to_callback('define_font',luatexja.font_callback,"luatexja.font_callback", 1)
396 end
397
398 ------------------------------------------------------------------------
399 -- LATEX INTERFACE
400 ------------------------------------------------------------------------
401 do
402    -- these function are called from ltj-latex.sty
403    local fenc_list, kyenc_list, ktenc_list = {}, {}, {}
404    function add_fenc_list(enc) fenc_list[enc] = 'true ' end
405    function add_kyenc_list(enc) kyenc_list[enc] = 'true ' end
406    function add_ktenc_list(enc) ktenc_list[enc] = 'true ' end
407    function is_kyenc(enc)
408       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
409    end
410    function is_ktenc(enc)
411       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (ktenc_list[enc] or 'false '))
412    end
413    function is_kenc(enc)
414       tex.sprint(cat_lp, '\\let\\ifin@\\if'
415                  .. (kyenc_list[enc] or ktenc_list[enc] or 'false '))
416    end
417
418    local kfam_list, Nkfam_list = {}, {}
419    function add_kfam(fam)
420       kfam_list[fam]=true
421    end
422    function search_kfam(fam, use_fd)
423       if kfam_list[fam] then
424          tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
425       elseif Nkfam_list[fam] then
426          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
427       elseif use_fd then
428          for i,_ in pairs(kyenc_list) do
429             if kpse.find_file(string.lower(i)..fam..'.fd') then
430                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
431             end
432          end
433          for i,_ in pairs(ktenc_list) do
434             if kpse.find_file(string.lower(i)..fam..'.fd') then
435                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
436             end
437          end
438          Nkfam_list[fam]=true; tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
439       else
440          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
441       end
442    end
443    local ffam_list, Nffam_list = {}, {}
444    function is_ffam(fam)
445       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (ffam_list[fam] or 'false '))
446    end
447    function add_ffam(fam)
448       ffam_list[fam]='true '
449    end
450    function search_ffam_declared()
451      local s = ''
452      for i,_ in pairs(fenc_list) do
453         s = s .. '\\cdp@elt{' .. i .. '}'
454      end
455      tex.sprint(cat_lp, s)
456    end
457    function search_ffam_fd(fam)
458       if Nffam_list[fam] then
459          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
460       else
461          for i,_ in pairs(fenc_list) do
462             if kpse.find_file(string.lower(i)..fam..'.fd') then
463                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
464             end
465          end
466          Nffam_list[fam]=true; tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
467       end
468    end
469
470 end
471 ------------------------------------------------------------------------
472 -- ALTERNATE FONTS
473 ------------------------------------------------------------------------
474 alt_font_table = {}
475 local alt_font_table = alt_font_table
476 local attr_curaltfnt = {}
477 local ucs_out = 0x110000
478
479 ------ for TeX interface
480 -- EXT
481 function set_alt_font(b,e,ind,bfnt)
482    -- ind: 新フォント, bfnt: 基底フォント
483    if b>e then b, e = e, b end
484    if b*e<=0 then
485       ltjb.package_error('luatexja',
486                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
487                            'I take the intersection with [0x80, 0x10ffff].')
488       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
489    elseif e<0 then -- b<e<0
490       -- do nothing
491    elseif b<0x80 or e>=ucs_out then
492       ltjb.package_warning('luatexja',
493                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
494                               'I take the intersection with [0x80, 0x10ffff].')
495       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
496    end
497    if not alt_font_table[bfnt] then alt_font_table[bfnt]={} end
498    local t = alt_font_table[bfnt]
499    local ac = font_getfont(ind).characters
500    if bfnt==ind then ind = nil end -- ind == bfnt の場合はテーブルから削除
501    if e>=0 then -- character range
502       for i=b, e do
503          if ac[i]then  t[i]=ind end
504       end
505    else
506       b, e = -e, -b
507       local tx = font_metric_table[bfnt].chars
508       for i,v in pairs(tx) do
509          if b<=v and v<=e and ac[i] then t[i]=ind end
510       end
511    end
512 end
513
514 -- EXT
515 function clear_alt_font(bfnt)
516    if alt_font_table[bfnt] then
517       local t = alt_font_table[bfnt]
518       for i,_ in pairs(t) do t[i]=nil; end
519    end
520 end
521
522 ------ used in ltjp.suppress_hyphenate_ja callback
523 function replace_altfont(pf, pc)
524    local a = alt_font_table[pf]
525    return a and a[pc] or pf
526 end
527
528 ------ for LaTeX interface
529
530 local alt_font_table_latex = {}
531
532 -- EXT
533 function clear_alt_font_latex(bbase)
534    local t = alt_font_table_latex[bbase]
535    if t then
536       for j,v in pairs(t) do t[j] = nil end
537    end
538 end
539
540 -- EXT
541 function set_alt_font_latex(b,e,ind,bbase)
542    -- ind: Alt font の enc/fam/ser/shape, bbase: 基底フォントの enc/fam/ser/shape
543    if b>e then b, e = e, b end
544    if b*e<=0 then
545       ltjb.package_error('luatexja',
546                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
547                            'I take the intersection with [0x80, 0x10ffff].')
548       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
549    elseif e<0 then -- b<e<0
550       -- do nothing
551    elseif b<0x80 or e>=ucs_out then
552       ltjb.package_warning('luatexja',
553                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
554                               'I take the intersection with [0x80, 0x10ffff].')
555       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
556    end
557
558    if not alt_font_table_latex[bbase] then alt_font_table_latex[bbase]={} end
559    local t = alt_font_table_latex[bbase]
560    if not t[ind] then t[ind] = {} end
561    for i=b, e do
562       for j,v in pairs(t) do
563          if v[i] then -- remove old entry
564             if j~=ind then v[i]=nil end; break
565          end
566       end
567       t[ind][i]=true
568    end
569    -- remove the empty tables
570    for j,v in pairs(t) do
571       local flag_clear = true
572       for k,_ in pairs(v) do flag_clear = false; break end
573       if flag_clear then t[j]=nil end
574    end
575    if ind==bbase  then t[bbase] = nil end
576 end
577
578 -- ここから先は 新 \selectfont の内部でしか実行されない
579 do
580    local alt_font_base, alt_font_base_num
581    local aftl_base
582    -- EXT
583    function does_alt_set(bbase)
584       aftl_base = alt_font_table_latex[bbase]
585       tex.sprint(cat_lp, '\\if' .. (aftl_base and 'true' or 'false'))
586    end
587    -- EXT
588    function print_aftl_address()
589       tex.sprint(cat_lp, ';ltjaltfont' .. tostring(aftl_base):sub(8))
590    end
591
592 -- EXT
593    function output_alt_font_cmd(dir, bbase)
594       alt_font_base = bbase
595       if dir == 't' then
596          alt_font_base_num = tex.getattribute(attr_curtfnt)
597       else
598          alt_font_base_num = tex.getattribute(attr_curjfnt)
599       end
600       local t = alt_font_table[alt_font_base_num]
601       if t then
602          for i,_ in pairs(t) do t[i]=nil end
603       end
604       t = alt_font_table_latex[bbase]
605       if t then
606        for i,_ in pairs(t) do
607             tex.sprint(cat_lp, '\\ltj@pickup@altfont@aux' .. dir .. '{' .. i .. '}')
608          end
609       end
610    end
611
612 -- EXT
613    function pickup_alt_font_a(size_str)
614       local t = alt_font_table_latex[alt_font_base]
615       if t then
616          for i,v in pairs(t) do
617             tex.sprint(cat_lp, '\\expandafter\\ltj@pickup@altfont@copy'
618                           .. '\\csname ' .. i .. '/' .. size_str .. '\\endcsname{' .. i .. '}')
619          end
620       end
621    end
622
623    local function pickup_alt_font_class(class, afnt_num, afnt_chars)
624       local t  = alt_font_table[alt_font_base_num]
625       local tx = font_metric_table[alt_font_base_num].chars
626       for i,v in pairs(tx) do
627          if v==class and afnt_chars[i] then t[i]=afnt_num end
628       end
629    end
630
631 -- EXT
632    function pickup_alt_font_b(afnt_num, afnt_base)
633       local t = alt_font_table[alt_font_base_num]
634       local ac = font_getfont(afnt_num).characters
635       if not t then t = {}; alt_font_table[alt_font_base_num] = t end
636       for i,v in pairs(alt_font_table_latex[alt_font_base]) do
637          if i == afnt_base then
638             for j,_ in pairs(v) do
639                if j>=0 then
640                   if ac[j] then t[j]=afnt_num end
641                else  -- -n (n>=1) means that the character class n,
642                      -- which is defined in the JFM
643                   pickup_alt_font_class(-j, afnt_num, ac)
644                end
645             end
646             return
647          end
648       end
649    end
650
651 end
652 ------------------------------------------------------------------------
653 -- 終了時に各種ノードを破棄
654 ------------------------------------------------------------------------
655 do
656    function cleanup_size_cache()
657       --local gs, ke = 0, 0
658       for _,n in pairs(metrics) do
659          for i,t in pairs(n.size_cache) do
660             for _,v in pairs(t.char_type) do
661                for k,w in pairs(v) do
662                   if type(k)=='number' then
663                      --if w[1] then gs = gs + 1 else ke = ke + 1 end
664                      node_free(w[2])
665                   end
666                end
667             end
668             n.size_cache[i]=nil
669          end
670       end
671       --print('glue spec: ', gs, 'kern: ', ke)
672    end
673 end
674
675 ------------------------------------------------------------------------
676 -- 追加のフォント情報
677 ------------------------------------------------------------------------
678 font_extra_info = {}
679 local font_extra_info = font_extra_info -- key: fontnumber
680 local font_extra_basename = {} -- key: basename
681
682 -- IVS and vertical metrics
683 local prepare_fl_data
684 local supply_vkern_table
685 do
686    local fields = fontloader.fields
687    local function glyph_vmetric(glyph)
688       local flds = fields(glyph)
689       local vw, tsb, vk = nil, nil, nil
690       for _,i in ipairs(flds) do
691          if i=='vwidth' then vw = glyph.vwidth end
692          if i=='tsidebearing' then tsb = glyph.tsidebearing end
693          if i=='vkerns' then vk = glyph.vkerns end
694       end
695       return vw, tsb, vk
696    end
697
698    local sort = table.sort
699    local function add_fl_table(dest, glyphs, unitable, asc_des, units)
700       local tg, glyphmin, glyphmax = glyphs.glyphs, 0, glyphs.glyphmax
701       for _,v in pairs(fields(glyphs)) do
702          if v=='glyphmin' then glyphmin, glyphmax = glyphs.glyphmin, glyphmax+1; break end
703       end
704       for i = glyphmin, glyphmax-1 do
705          local gv = tg[i]
706          if gv then
707             if gv.altuni then
708                for _,at in pairs(gv.altuni) do
709                   local bu, vsel = at.unicode, at.variant
710                   if vsel then
711                      if vsel>=0xE0100 then vsel = vsel - 0xE0100 end
712                      dest = dest or {}; dest[bu] = dest[bu] or {}
713                      local uniq_flag = true
714                      for i,_ in pairs(dest[bu]) do
715                         if i==vs then uniq_flag = false; break end
716                      end
717                      if uniq_flag then
718                         dest[bu][vsel] = unitable[gv.name]
719                      end
720                   end
721                end
722             end
723             -- vertical metric
724             local vw, tsb, vk = glyph_vmetric(gv)
725             local gi = unitable[gv.name]
726             if gi and vw and vw~=asc_des then
727                -- We do not use tsidebearing, since (1) fontloader does not read VORG table
728                -- and (2) 'tsidebearing' doea not appear in the returned table by fontloader.fields.
729                -- Hence, we assume that vertical origin == ascender
730                -- (see capsule_glyph_tate in ltj-setwidth.lua)
731                dest = dest or {}; dest[gi] = dest[gi] or {}
732                dest[gi].vwidth = vw/units
733             end
734             -- vertical kern
735             if gi and vk then
736                dest = dest or {};
737                local dest_vk = dest.vkerns or {}; dest.vkerns = dest_vk
738                for _,v in pairs(vk) do
739                   if unitable[v.char] then
740                      local vl = v.lookup
741                      if type(vl)=='table' then
742                         for _,vlt in pairs(vl) do
743                            dest_vk[vlt] = dest_vk[vlt] or {}
744                            dest_vk[vlt][gi] = dest_vk[vlt][gi] or {}
745                            dest_vk[vlt][gi][unitable[v.char]] = v.off
746                         end
747                      else
748                         dest_vk[vl] = dest_vk[vl] or {}
749                         dest_vk[vl][gi] = dest_vk[vl][gi] or {}
750                         dest_vk[vl][gi][unitable[v.char]] = v.off
751                      end
752                   end
753                end
754             end
755          end
756       end
757       return dest
758    end
759    prepare_fl_data = function (dest, id)
760       local fl = fontloader.open(id.filename)
761       local unicodes = id.resources.unicodes
762       if fl.glyphs then
763          dest = add_fl_table(dest, fl, unicodes,
764                              fl.ascent + fl.descent, fl.units_per_em)
765       end
766       if fl.subfonts then
767          for _,v in pairs(fl.subfonts) do
768             dest = add_fl_table(dest, v, unicodes,
769                                 fl.ascent + fl.descent, fl.units_per_em)
770          end
771       end
772       fontloader.close(fl); collectgarbage("collect")
773       return dest
774    end
775    -- supply vkern table
776    supply_vkern_table = function(id, bname)
777       local bx = font_extra_basename[bname].vkerns
778       local lookuphash =  id.resources.lookuphash
779       local desc = id.shared.rawdata.descriptions
780       if bx and lookuphash then
781          for i,v in pairs(bx) do
782             lookuphash[i] = lookuphash[i] or v
783             for j,w in pairs(v) do
784                desc[j].kerns = desc[j].kerns or {}
785                desc[j].kerns[i] = w
786             end
787          end
788       end
789    end
790 end
791
792 --
793 do
794    local cache_ver = 6
795    local checksum = file.checksum
796
797    local function prepare_extra_data_base(id)
798       if not id then return end
799       local bname = file.nameonly(id.filename or '')
800       if not font_extra_basename[bname] then
801          -- if the cache is present, read it
802          local newsum = checksum(id.filename) -- MD5 checksum of the fontfile
803          local v = "extra_" .. string.lower(file.nameonly(id.filename))
804          local dat = ltjb.load_cache(
805             v,
806             function (t) return (t.version~=cache_ver) or (t.chksum~=newsum) end
807          )
808          -- if the cache is not found or outdated, save the cache
809          if dat then
810             font_extra_basename[bname] = dat[1] or {}
811          else
812             local dat = nil
813             dat = prepare_fl_data(dat, id)
814             font_extra_basename[bname] = dat or {}
815             ltjb.save_cache( v,
816                              {
817                                 chksum = checksum(id.filename),
818                                 version = cache_ver,
819                                 dat,
820                              })
821          end
822          return bname
823       end
824    end
825    local function prepare_extra_data_font(id, res)
826       if type(res)=='table' and res.shared then
827          font_extra_info[id] = font_extra_basename[file.nameonly(res.filename)]
828       end
829    end
830     luatexbase.add_to_callback(
831        'luaotfload.patch_font',
832        function (tfmdata)
833           -- these function is executed one time per one fontfile
834           local bname = prepare_extra_data_base(tfmdata)
835           if bname then supply_vkern_table(tfmdata, bname) end
836           return tfmdata
837        end,
838        'ltj.prepare_extra_data', 1)
839    luatexbase.add_to_callback(
840       'luatexja.define_font',
841       function (res, name, size, id)
842          prepare_extra_data_font(id, res)
843       end,
844       'ltj.prepare_extra_data', 1)
845
846    local nulltable = {} -- dummy
847    ltjr.vert_addfunc = function (n) font_extra_info[n] = nulltable end
848
849    local identifiers = fonts.hashes.identifiers
850    for i=1,font.nextid()-1 do
851       if identifiers[i] then
852          prepare_extra_data_base(identifiers[i])
853          prepare_extra_data_font(i,identifiers[i])
854       end
855    end
856 end
857
858
859 ------------------------------------------------------------------------
860 -- calculate vadvance
861 ------------------------------------------------------------------------
862 do
863    local function acc_feature(table_vadv, table_vorg, subtables, ft,  already_vert)
864       for char_num,v in pairs(ft.shared.rawdata.descriptions) do
865          if v.slookups then
866             for sn, sv in pairs(v.slookups) do
867                if subtables[sn] and type(sv)=='table' then
868                   if sv[4]~=0 then
869                      table_vadv[char_num]
870                         = (table_vadv[char_num] or 0) + sv[4]
871                   end
872                   if sv[2]~=0 and not already_vert then
873                      table_vorg[char_num]
874                         = (table_vorg[char_num] or 0) + sv[2]
875                   end
876                end
877             end
878          end
879       end
880    end
881
882 luatexbase.add_to_callback(
883    "luatexja.define_jfont",
884    function (fmtable, fnum)
885       local vadv = {}; fmtable.v_advance = vadv
886       local vorg = {}; fmtable.v_origin = vorg
887       local ft = font_getfont(fnum)
888       local subtables = {}
889       if ft.specification then
890          for feat_name,v in pairs(ft.specification.features.normal) do
891             if v==true then
892                for _,i in pairs(ft.resources.sequences) do
893                   if i.order[1]== feat_name and i.type == 'gpos_single' then
894                      for _,st in pairs(i.subtables) do
895                         subtables[st] = true
896                      end
897                   end
898                end
899             end
900          end
901          acc_feature(vadv, vorg, subtables, ft,
902                      ft.specification.features.normal.vrt2 or ft.specification.features.normal.vert)
903          for i,v in pairs(vadv) do
904             vadv[i]=vadv[i]/ft.units_per_em*fmtable.size
905          end
906          for i,v in pairs(vorg) do
907             vorg[i]=vorg[i]/ft.units_per_em*fmtable.size
908          end
909       end
910       return fmtable
911    end, 1, 'ltj.v_advance'
912 )
913 end
914
915 ------------------------------------------------------------------------
916 -- supply tounicode entries
917 ------------------------------------------------------------------------
918 do
919   local ltjr_prepare_cid_font = ltjr.prepare_cid_font
920   luatexbase.add_to_callback(
921      'luaotfload.patch_font',
922      function (tfmdata)
923         if tfmdata.cidinfo then
924            local rd = ltjr_prepare_cid_font(tfmdata.cidinfo.registry, tfmdata.cidinfo.ordering)
925            if rd then
926               local ru, rc = rd.resources.unicodes, rd.characters
927               for i,v in pairs(tfmdata.characters) do
928                  local w = ru["Japan1." .. tostring(v.index)]
929                  if w then
930                     v.tounicode = v.tounicode or rc[w]. tounicode
931                  end
932               end
933            end
934         end
935
936         return tfmdata
937      end,
938      'ltj.supply_tounicode', 1)
939 end
940
941
942 ------------------------------------------------------------------------
943 -- MISC
944 ------------------------------------------------------------------------
945 do
946    local getfont = (Dnode ~= node) and Dnode.getfont or function(n) return n.font end
947    local getchar = (Dnode ~= node) and Dnode.getchar or function(n) return n.char end
948    local get_dir_count = ltjd.get_dir_count
949    local is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char_direct
950    local ensure_tex_attr = ltjb.ensure_tex_attr
951    local node_write = Dnode.write
952    local font = font
953    local new_ic_kern
954    if status.luatex_version>=89 then
955        new_ic_kern = function(g)  return node_new(id_kern,3) end
956    else
957        local ITALIC       = luatexja.icflag_table.ITALIC
958        new_ic_kern = function()
959          local g = node_new(id_kern)
960          setfield(g, 'subtype', 1); set_attr(g, attr_icflag, ITALIC)
961          return g
962        end
963    end
964    -- EXT: italic correction
965    function append_italic()
966       local p = to_direct(tex.nest[tex.nest.ptr].tail)
967       local TEMP = node_new(id_kern)
968       if p and getid(p)==id_glyph then
969          if is_ucs_in_japanese_char(p) then
970             local j = font_metric_table[
971                has_attr(p, (get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)
972                ]
973             local g = new_ic_kern()
974             setfield(g, 'kern', j.char_type[find_char_class(getchar(p), j)].italic)
975             node_write(g); ensure_tex_attr(attr_icflag, 0)
976          else
977             local f = getfont(p)
978             local h = font_getfont(f) or font.fonts[f]
979             if h then
980                local g = new_ic_kern()
981                if h.characters[getchar(p)] and h.characters[getchar(p)].italic then
982                   setfield(g, 'kern', h.characters[getchar(p)].italic)
983                   node_write(g); ensure_tex_attr(attr_icflag, 0)
984                end
985             end
986          end
987       end
988       node_free(TEMP)
989    end
990 end
991
992 ------------------------------------------------------------------------
993 -- VERT VARIANT TABLE
994 ------------------------------------------------------------------------
995 vert_form_table = {
996    [0x2013]=0xFE32, [0x2014]=0xFE31, [0x2025]=0xFE30,
997    [0xFF08]=0xFE35, [0xFF09]=0xFE36, [0xFF5B]=0xFE37, [0xFF5D]=0xFE38,
998    [0x3014]=0xFE39, [0x3015]=0xFE3A, [0x3010]=0xFE3B, [0x3011]=0xFE3C,
999    [0x300A]=0xFE3D, [0x300B]=0xFE3E, [0x3008]=0xFE3F, [0x3009]=0xFE40,
1000    [0x300C]=0xFE41, [0x300D]=0xFE42, [0x300E]=0xFE43, [0x300F]=0xFE44,
1001    [0xFF3B]=0xFE47, [0xFF3D]=0xFE48, [0xFF3F]=0xFE33,
1002 }
1003 setmetatable(vert_form_table, {__index=function(t,k) return k end});