OSDN Git Service

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