OSDN Git Service

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