OSDN Git Service

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