OSDN Git Service

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