OSDN Git Service

Bugfix of the previous commit.
[luatex-ja/luatexja.git] / src / ltj-jfont.lua
1 --
2 -- luatexja/jfont.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfont',
6   date = '2014/10/03',
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 local getfont = (Dnode ~= node) and Dnode.getfont or function(n) return n.font end
22 local getchar = (Dnode ~= node) and Dnode.getchar or function(n) return n.char end
23
24 local nullfunc = function(n) return n end
25 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
26
27 local node_new = Dnode.new
28 local node_free = Dnode.free
29 local has_attr = Dnode.has_attribute
30 local set_attr = Dnode.set_attribute
31 local node_write = Dnode.write
32 local round = tex.round
33 local font_getfont = font.getfont
34
35 local attr_icflag = luatexbase.attributes['ltj@icflag']
36 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
37 local attr_curtfnt = luatexbase.attributes['ltj@curtfnt']
38 local id_glyph = node.id('glyph')
39 local id_kern = node.id('kern')
40 local id_glue_spec = node.id('glue_spec')
41 local id_glue = node.id('glue')
42 local cat_lp = luatexbase.catcodetables['latex-package']
43 local ITALIC       = luatexja.icflag_table.ITALIC
44 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
45
46 ------------------------------------------------------------------------
47 -- LOADING JFM
48 ------------------------------------------------------------------------
49
50 metrics={} -- this table stores all metric informations
51 font_metric_table={} -- [font number] -> jfm_name, jfm_var, size
52
53 luatexbase.create_callback("luatexja.load_jfm", "data", function (ft, jn) return ft end)
54
55 local jfm_file_name, jfm_var
56 local defjfm_res
57 local jfm_dir
58
59 function define_jfm(t)
60    local real_char -- Does current character class have the 'real' character?
61    if t.dir~=jfm_dir then
62       defjfm_res= nil; return
63    elseif type(t.zw)~='number' or type(t.zh)~='number' then
64       defjfm_res= nil; return
65    end
66    t.char_type = {}; t.chars = {}
67    for i,v in pairs(t) do
68       if type(i) == 'number' then -- char_type
69          if not v.chars then
70             if i ~= 0 then defjfm_res= nil; return  end
71             real_char = true
72          else
73             real_char = false
74             for j,w in pairs(v.chars) do
75                if type(w) == 'number' and w~=-1 then
76                   real_char = true;
77                elseif type(w) == 'string' and utf.len(w)==1 then
78                   real_char = true; w = utf.byte(w)
79                elseif type(w) == 'string' and utf.len(w)==2 and utf.sub(w,2) == '*' then
80                   real_char = true; w = utf.byte(utf.sub(w,1,1))
81                   if not t.chars[-w] then
82                      t.chars[-w] = i
83                   else
84                      defjfm_res= nil; return
85                   end
86                end
87                if not t.chars[w] then
88                   t.chars[w] = i
89                else
90                   defjfm_res= nil; return
91                end
92             end
93             if type(v.align)~='string' then
94                v.align = 'left' -- left
95             end
96             if real_char then
97                if type(v.width)~='number' and v.width~='prop' then
98                   defjfm_res= nil; return
99                else
100                   if v.width=='prop' and jfm_dir=='tate' then
101                      v.width = 1.0
102                   end
103                   if type(v.height)~='number' then
104                      v.height = 0.0
105                   end
106                   if type(v.depth)~='number' then
107                      v.depth = 0.0
108                   end
109                   if type(v.italic)~='number' then
110                      v.italic = 0.0
111                   end
112                   if type(v.left)~='number' then
113                      v.left = 0.0
114                   end
115                   if type(v.down)~='number' then
116                      v.down = 0.0
117                   end
118                end
119             end
120             v.chars = nil
121          end
122          v.kern = v.kern or {}; v.glue = v.glue or {}
123          for j in pairs(v.glue) do
124             if v.kern[j] then defjfm_res= nil; return end
125          end
126          for j,x in pairs(v.kern) do
127             if type(x)=='number' then
128                v.kern[j] = {x, 0}
129             elseif type(x)=='table' then
130                v.kern[j] = {x[1], x[2] or 0}
131             end
132          end
133          t.char_type[i] = v
134          t[i] = nil
135       end
136    end
137    t = luatexbase.call_callback("luatexja.load_jfm", t, jfm_file_name)
138    t.size_cache = {}
139    defjfm_res = t
140 end
141
142 local update_jfm_cache
143 do
144    local function mult_table(old,scale) -- modified from table.fastcopy
145       if old then
146          local new = { }
147          for k,v in next, old do
148             if type(v) == "table" then
149                new[k] = mult_table(v,scale)
150             elseif type(v) == "number" then
151                new[k] = round(v*scale)
152             else
153                new[k] = v
154             end
155          end
156          return new
157       else return nil end
158    end
159
160    update_jfm_cache = function (j,sz)
161       if metrics[j].size_cache[sz] then return end
162       local t = {}
163       metrics[j].size_cache[sz] = t
164       t.chars = metrics[j].chars
165       t.char_type = mult_table(metrics[j].char_type, sz)
166       for i,v in pairs(t.char_type) do
167          v.align = (v.align=='left') and 0 or
168             ((v.align=='right') and 1 or 0.5)
169          if type(i) == 'number' then -- char_type
170             for k,w in pairs(v.glue) do
171                local h = node_new(id_glue_spec)
172                v[k] = {true, h, (w[5] and w[5]/sz or 0), FROM_JFM + (w[4] and w[4]/sz or 0)}
173                setfield(h, 'width', w[1])
174                setfield(h, 'stretch', w[2])
175                setfield(h, 'shrink', w[3])
176                setfield(h, 'stretch_order', 0)
177                setfield(h, 'shrink_order', 0)
178             end
179             for k,w in pairs(v.kern) do
180                local g = node_new(id_kern)
181                setfield(g, 'kern', w[1])
182                setfield(g, 'subtype', 1)
183                set_attr(g, attr_icflag, FROM_JFM)
184                v[k] = {false, g, w[2]/sz}
185             end
186          end
187          v.glue, v.kern = nil, nil
188       end
189       t.kanjiskip = mult_table(metrics[j].kanjiskip, sz)
190       t.xkanjiskip = mult_table(metrics[j].xkanjiskip,sz)
191       t.zw = round(metrics[j].zw*sz)
192       t.zh = round(metrics[j].zh*sz)
193       t.size = sz
194    end
195 end
196
197 luatexbase.create_callback("luatexja.find_char_class", "data",
198                            function (arg, fmtable, char)
199                               return 0
200                            end)
201 do
202    local start_time_measure = ltjb.start_time_measure
203    local stop_time_measure = ltjb.stop_time_measure
204    local fcc_temp = { chars_cbcache = {} }
205    setmetatable(
206       fcc_temp.chars_cbcache,
207       {
208          __index = function () return 0 end,
209       })
210    function find_char_class(c,m)
211       -- c: character code, m:
212       local r = (m or fcc_temp).chars_cbcache[c]
213       if not r then
214          r = m.chars[c] or
215             luatexbase.call_callback("luatexja.find_char_class", 0, m, c)
216          m.chars_cbcache[c or 0] = r
217       end
218       return r
219    end
220 end
221
222
223 ------------------------------------------------------------------------
224 -- LOADING JAPANESE FONTS
225 ------------------------------------------------------------------------
226
227 do
228    local cstemp
229    local global_flag -- true if \globaljfont, false if \jfont
230    local function load_jfont_metric()
231       if jfm_file_name=='' then
232          ltjb.package_error('luatexja',
233                             'no JFM specified',
234                             'To load and define a Japanese font, a JFM must be specified.'..
235                             "The JFM 'ujis' will be  used for now.")
236          jfm_file_name='ujis'
237       end
238       for j,v in ipairs(metrics) do
239          if v.name==jfm_file_name then return j end
240       end
241       luatexja.load_lua('jfm-' .. jfm_file_name .. '.lua')
242       if defjfm_res then
243          defjfm_res.name = jfm_file_name
244          table.insert(metrics, defjfm_res)
245          return #metrics
246       else
247          return nil
248       end
249    end
250
251 -- EXT
252    function jfontdefX(g)
253       local t = token.get_next()
254       cstemp=token.csname_name(t)
255       global_flag = g and '\\global' or ''
256       tex.sprint(cat_lp, '\\expandafter\\font\\csname ', cstemp, '\\endcsname')
257    end
258
259    luatexbase.create_callback("luatexja.define_jfont", "data", function (ft, fn) return ft end)
260
261 -- EXT
262    local identifiers = fonts.hashes.identifiers
263    function jfontdefY(dir)
264       jfm_dir = dir
265       local j = load_jfont_metric(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 ', cstemp,
274                        '\\endcsname=\\relax')
275          return
276       end
277       update_jfm_cache(j, f.size)
278       local ad = identifiers[fn].parameters
279       local sz = metrics[j].size_cache[f.size]
280       local fmtable = { jfm = j, size = f.size, var = jfm_var,
281                         zw = sz.zw, zh = sz.zh,
282                         ascent = ad.ascender,
283                         descent = ad.descender,
284                         chars = sz.chars, char_type = sz.char_type,
285                         kanjiskip = sz.kanjiskip, xkanjiskip = sz.xkanjiskip,
286                         chars_cbcache = {},
287       }
288
289       fmtable = luatexbase.call_callback("luatexja.define_jfont", fmtable, fn)
290       font_metric_table[fn]=fmtable
291       tex.sprint(cat_lp, global_flag, '\\protected\\expandafter\\def\\csname ',
292                     cstemp , '\\endcsname{\\ltj@cur'..
293                     (dir == 'yoko' and 'j' or 't') .. 'fnt', fn, '\\relax}')
294    end
295 end
296
297 do
298    local get_dir_count = ltjd.get_dir_count
299    local dir_tate = luatexja.dir_table.dir_tate
300    local tex_get_attr = tex.getattribute
301    -- PUBLIC function
302    function get_zw()
303       local a = font_metric_table[
304          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
305       return a and a.zw or 0
306    end
307    function get_zh()
308       local a = font_metric_table[
309          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
310       return a and a.zw or 0
311    end
312 end
313
314 do
315    -- extract jfm_file_name and jfm_var
316    -- normalize position of 'jfm=' and 'jfmvar=' keys
317    local function extract_metric(name)
318       jfm_file_name = ''; jfm_var = ''
319       local tmp, index = name:sub(1, 5), 1
320       if tmp == 'file:' or tmp == 'name:' or tmp == 'psft:' then
321          index = 6
322       end
323       local p = name:find(":", index); index = p and (p+1) or index
324       while index do
325          local l = name:len()+1
326          local q = name:find(";", index+1) or l
327          if name:sub(index, index+3)=='jfm=' and q>index+4 then
328             jfm_file_name = name:sub(index+4, q-1)
329             if l~=q then
330                name = name:sub(1,index-1) .. name:sub(q+1)
331             else
332                name = name:sub(1,index-1)
333                index = nil
334             end
335          elseif name:sub(index, index+6)=='jfmvar=' and q>index+6 then
336             jfm_var = name:sub(index+7, q-1)
337             if l~=q then
338                name = name:sub(1,index-1) .. name:sub(q+1)
339             else
340                name = name:sub(1,index-1)
341                index = nil
342             end
343          else
344             index = (l~=q) and (q+1) or nil
345          end
346       end
347       if jfm_file_name~='' then
348          local l = name:sub(-1)
349          name = name
350             .. ((l==':' or l==';') and '' or ';')
351             .. 'jfm=' .. jfm_file_name
352          if jfm_var~='' then
353             name = name .. 'jfmvar=' .. jfm_var
354          end
355       end
356       return name
357    end
358
359    -- define_font callback
360    local otfl_fdr = fonts.definers.read
361    local ltjr_font_callback = ltjr.font_callback
362    function luatexja.font_callback(name, size, id)
363       local new_name = extract_metric(name)
364       local res =  ltjr_font_callback(new_name, size, id, otfl_fdr)
365       luatexbase.call_callback('luatexja.define_font', res, new_name, size, id)
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 ------------------------------------------------------------------------
608 font_extra_info = {}
609 local font_extra_info = font_extra_info -- key: fontnumber
610 local font_extra_basename = {} -- key: basename
611
612 -- IVS and vertical metrics
613 local prepare_fl_data
614 local supply_vkern_table
615 do
616    local fields = fontloader.fields
617    local function glyph_vmetric(glyph)
618       local flds = fields(glyph)
619       local vw, tsb, vk = nil, nil, nil
620       for _,i in ipairs(flds) do
621          if i=='vwidth' then vw = glyph.vwidth end
622          if i=='tsidebearing' then tsb = glyph.tsidebearing end
623          if i=='vkerns' then vk = glyph.vkerns end
624       end
625       return vw, tsb, vk
626    end
627    
628    local sort = table.sort
629    local function add_fl_table(dest, tg, unitable, glyphmax, asc_des, units)
630       for i = 0, glyphmax-1 do
631          local gv = tg[i]
632          if gv then
633             if gv.altuni then
634                for _,at in pairs(gv.altuni) do
635                   local bu, vsel = at.unicode, at.variant
636                   if vsel then
637                      if vsel>=0xE0100 then vsel = vsel - 0xE0100 end
638                      dest = dest or {}; dest[bu] = dest[bu] or {}
639                      local uniq_flag = true
640                      for i,_ in pairs(dest[bu]) do
641                         if i==vs then uniq_flag = false; break end
642                      end
643                      if uniq_flag then
644                         dest[bu][vsel] = unitable[gv.name]
645                      end
646                   end
647                end
648             end
649             -- vertical metric
650             local vw, tsb, vk = glyph_vmetric(gv)
651             local gi = unitable[gv.name]
652             if vw and vw~=asc_des then
653                -- We do not use tsidebearing, since (1) fontloader does not read VORG table
654                -- and (2) 'tsidebearing' doea not appear in the returned table by fontloader.fields.
655                -- Hence, we assume that vertical origin == ascender
656                -- (see capsule_glyph_tate in ltj-setwidth.lua)
657                dest = dest or {}; dest[gi] = dest[gi] or {}
658                dest[gi].vwidth = vw/units
659             end
660             -- vertical kern
661             if vk then
662                dest = dest or {}; 
663                local dest_vk = dest.vkerns or {}; dest.vkerns = dest_vk
664                for _,v in pairs(vk) do
665                   dest_vk[v.lookup] = dest_vk[v.lookup] or {}
666                   dest_vk[v.lookup][gi] = dest_vk[v.lookup][gi] or {}
667                   dest_vk[v.lookup][gi][unitable[v.char]] = v.off
668                end
669             end
670          end
671       end
672       return dest
673    end
674    prepare_fl_data = function (dest, id)
675       local fl = fontloader.open(id.filename)
676       local unicodes = id.resources.unicodes
677       if fl.glyphs then
678          dest = add_fl_table(dest, fl.glyphs, id.resources.unicodes, fl.glyphmax,
679                              fl.ascent + fl.descent, fl.units_per_em)
680       end
681       if fl.subfonts then
682          for _,v in pairs(fl.subfonts) do
683             dest = add_fl_table(dest, v.glyphs, id.resources.unicodes, v.glyphmax,
684                                 fl.ascent + fl.descent, fl.units_per_em)
685          end
686       end
687       fontloader.close(fl)
688       return dest
689    end
690    -- supply vkern table
691    supply_vkern_table = function(id, bname)
692       local bx = font_extra_basename[bname].vkerns
693       local lookuphash =  id.resources.lookuphash
694       local desc = id.shared.rawdata.descriptions
695       if bx then
696          for i,v in pairs(bx) do
697             lookuphash[i] = lookuphash[i] or v
698             for j,w in pairs(v) do
699                desc[j].kerns = desc[j].kerns or {}
700                desc[j].kerns[i] = w
701             end
702          end
703       end
704    end
705 end
706
707 -- 縦書き用字形への変換テーブル
708 local prepare_vert_data
709 do
710    local function add_feature_table(tname, src, dest)
711       for i,v in pairs(src) do
712          if type(v.slookups)=='table' then
713             local s = v.slookups[tname]
714             if s  then
715                dest = dest or {}
716                dest[i] = dest[i]  or {}
717                dest[i].vert = dest[i].vert or s
718             end
719          end
720       end
721       return dest
722    end
723    prepare_vert_data = function (dest, id) 
724       local a = id.resources.sequences
725       if a then
726          local s = id.shared.rawdata.descriptions
727          for i,v in pairs(a) do
728             if v.features.vert or v.features.vrt2 then
729                dest= add_feature_table(v.subtables[1], s, dest)
730             end
731          end
732       end
733       return dest
734    end
735    -- 縦書き用字形への変換
736    function get_vert_glyph(n, chr)
737       local fn = font_extra_info[n]
738       return (fn and fn[chr] and fn[chr].vert) or chr
739    end
740 end
741
742 -- 
743 do
744    local cache_ver = 3
745    local checksum = file.checksum
746
747    local function prepare_extra_data_base(id)
748       if not id then return end
749       local bname = file.nameonly(id.filename or '')
750       if not font_extra_basename[bname] then
751          -- if the cache is present, read it
752          local newsum = checksum(id.filename) -- MD5 checksum of the fontfile
753          local v = "extra_" .. string.lower(file.nameonly(id.filename))
754          local dat = ltjb.load_cache(
755             v,
756             function (t) return (t.version~=cache_ver) or (t.chksum~=newsum) end
757          )
758          -- if the cache is not found or outdated, save the cache
759          if dat then
760             font_extra_basename[bname] = dat[1] or {}
761          else
762             local dat = nil
763             dat = prepare_vert_data(dat, id)
764             dat = prepare_fl_data(dat, id)
765             font_extra_basename[bname] = dat or {}
766             ltjb.save_cache( v,
767                              {
768                                 chksum = checksum(id.filename),
769                                 version = cache_ver,
770                                 dat,
771                              })
772          end
773          return bname
774       end
775    end
776    local function prepare_extra_data_font(id, res)
777       if type(res)=='table' and res.shared then 
778          font_extra_info[id] = font_extra_basename[file.nameonly(res.filename)]
779       end
780    end
781     luatexbase.add_to_callback(
782        'luaotfload.patch_font',
783        function (tfmdata)
784           -- these function is executed one time per one fontfile
785           local bname = prepare_extra_data_base(tfmdata)
786           if bname then supply_vkern_table(tfmdata, bname) end
787        end,
788        'ltj.prepare_extra_data', 1)
789    luatexbase.add_to_callback(
790       'luatexja.define_font',
791       function (res, name, size, id)
792          prepare_extra_data_font(id, res)
793       end,
794       'ltj.prepare_extra_data', 1)
795
796    local function a (n, dat) font_extra_info[n] = dat end
797    ltjr.vert_addfunc = a
798
799    local identifiers = fonts.hashes.identifiers
800    for i=1,font.nextid()-1 do
801       if identifiers[i] then 
802          prepare_extra_data_base(identifiers[i])
803          prepare_extra_data_font(i,identifiers[i])
804       end
805    end
806 end
807
808
809 ------------------------------------------------------------------------
810 -- calculate vadvance
811 ------------------------------------------------------------------------
812 do
813    local function acc_feature(table_vadv, subtables, ft)
814       for char_num,v in pairs(ft.shared.rawdata.descriptions) do
815          if v.slookups then
816             for sn, sv in pairs(v.slookups) do
817                if subtables[sn] and type(sv)=='table' and sv[4]~=0 then
818                   table_vadv[char_num] 
819                      = (table_vadv[char_num] or 0) + sv[4]
820                end
821             end
822          end
823       end
824    end
825
826 luatexbase.add_to_callback(
827    "luatexja.define_jfont", 
828    function (fmtable, fnum)
829       local vadv = {}; fmtable.v_advance = vadv
830       local ft = font_getfont(fnum)
831       local subtables = {}
832       for feat_name,v in pairs(ft.specification.features.normal) do
833          if v then
834             for _,i in pairs(ft.resources.sequences) do
835                if i.order[1]== feat_name and i.type == 'gpos_single' then
836                   for _,st in pairs(i.subtables) do
837                      subtables[st] = true
838                   end
839                end
840             end
841          end
842       end
843       acc_feature(vadv, subtables, ft)
844       for i,v in pairs(vadv) do
845          vadv[i]=vadv[i]/ft.units_per_em*fmtable.size
846       end
847       return fmtable 
848    end, 1, 'ltj.v_advance'
849 )
850 end
851 ------------------------------------------------------------------------
852 -- MISC
853 ------------------------------------------------------------------------
854 do
855    local get_dir_count = ltjd.get_dir_count
856    local is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char_direct
857    local tex_set_attr = tex.setattribute
858    local font = font
859    -- EXT: italic correction
860    function append_italic()
861       local p = to_direct(tex.nest[tex.nest.ptr].tail)
862       if p and getid(p)==id_glyph then
863          local f = getfont(p)
864          local g = node_new(id_kern)
865          setfield(g, 'subtype', 1)
866          set_attr(g, attr_icflag, ITALIC)
867          if is_ucs_in_japanese_char(p) then
868             f = has_attr(p, (get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)
869             local j = font_metric_table[f]
870             setfield(g, 'kern', j.char_type[find_char_class(getchar(p), j)].italic)
871          else
872             local h = font_getfont(f) or font.fonts[f]
873             if h then
874                setfield(g, 'kern', h.characters[getchar(p)].italic)
875             else
876                tex_set_attr(attr_icflag, 0)
877                return node_free(g)
878             end
879          end
880          node_write(g)
881          tex_set_attr(attr_icflag, 0)
882       end
883    end
884 end
885