OSDN Git Service

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