OSDN Git Service

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