OSDN Git Service

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