OSDN Git Service

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