OSDN Git Service

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