OSDN Git Service

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