OSDN Git Service

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