OSDN Git Service

c3ffb6a57e480aa3cb25220c3d4e2f2711917779
[luatex-ja/luatexja.git] / src / ltj-jfont.lua
1 --
2 -- luatexja/jfont.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfont',
6   date = '2014/02/01',
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
14 local mem_leak_glue, mem_leak_gs, mem_leak_kern = 0, 0, 0
15
16 local Dnode = node.direct or node
17
18 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
19 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
20 local getfont = (Dnode ~= node) and Dnode.getfont or function(n) return n.font end
21 local getchar = (Dnode ~= node) and Dnode.getchar or function(n) return n.char end
22
23 local nullfunc = function(n) return n end
24 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
25
26 local node_new = Dnode.new
27 local node_free = Dnode.free
28 local has_attr = Dnode.has_attribute
29 local set_attr = Dnode.set_attribute
30 local node_write = Dnode.write
31 local round = tex.round
32 local font_getfont = font.getfont
33
34 local attr_icflag = luatexbase.attributes['ltj@icflag']
35 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
36 local id_glyph = node.id('glyph')
37 local id_kern = node.id('kern')
38 local id_glue_spec = node.id('glue_spec')
39 local id_glue = node.id('glue')
40 local cat_lp = luatexbase.catcodetables['latex-package']
41 local ITALIC       = luatexja.icflag_table.ITALIC
42 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
43
44 ------------------------------------------------------------------------
45 -- LOADING JFM
46 ------------------------------------------------------------------------
47
48 metrics={} -- this table stores all metric informations
49 font_metric_table={} -- [font number] -> jfm_name, jfm_var, size
50
51 luatexbase.create_callback("luatexja.load_jfm", "data", function (ft, jn) return ft end)
52
53 local jfm_file_name, jfm_var
54 local defjfm_res
55
56 function define_jfm(t)
57    local real_char -- Does current character class have the 'real' character?
58    if t.dir~='yoko' then
59       defjfm_res= nil; return
60    elseif type(t.zw)~='number' or type(t.zh)~='number' then 
61       defjfm_res= nil; return
62    end
63    t.char_type = {}; t.chars = {}
64    for i,v in pairs(t) do
65       if type(i) == 'number' then -- char_type
66          if not v.chars then
67             if i ~= 0 then defjfm_res= nil; return  end
68             real_char = true
69          else
70             real_char = false
71             for j,w in pairs(v.chars) do
72                if type(w) == 'number' then
73                   real_char = true;
74                elseif type(w) == 'string' and utf.len(w)==1 then
75                   real_char = true; w = utf.byte(w)
76                elseif type(w) == 'string' and utf.len(w)==2 and utf.sub(w,2) == '*' then
77                   real_char = true; w = utf.byte(utf.sub(w,1,1))
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 not t.chars[w] then
85                   t.chars[w] = i
86                else 
87                   defjfm_res= nil; return
88                end
89             end
90             if type(v.align)~='string' then 
91                v.align = 'left' -- left
92             end
93             if real_char then
94                if not (type(v.width)=='number' or v.width~='prop') then
95                   defjfm_res= nil; return
96                else
97                   if type(v.height)~='number' then
98                      v.height = 0.0
99                   end
100                   if type(v.depth)~='number' then
101                      v.depth = 0.0
102                   end
103                   if type(v.italic)~='number' then 
104                      v.italic = 0.0
105                   end
106                   if type(v.left)~='number' then 
107                      v.left = 0.0
108                   end
109                   if type(v.down)~='number' then 
110                      v.down = 0.0
111                   end
112                end
113             end
114             v.chars = nil
115          end
116          v.kern = v.kern or {}; v.glue = v.glue or {}
117          for j in pairs(v.glue) do
118             if v.kern[j] then defjfm_res= nil; return end
119          end
120          for j,x in pairs(v.kern) do
121             if type(x)=='number' then 
122                v.kern[j] = {x, 0}
123             elseif type(x)=='table' then 
124                v.kern[j] = {x[1], x[2] or 0}
125             end
126          end
127          t.char_type[i] = v
128          t[i] = nil
129       end
130    end
131    t = luatexbase.call_callback("luatexja.load_jfm", t, jfm_file_name)
132    t.size_cache = {}
133    defjfm_res = t
134 end
135
136 local update_jfm_cache
137 do
138    local function mult_table(old,scale) -- modified from table.fastcopy
139       if old then
140          local new = { }
141          for k,v in next, old do
142             if type(v) == "table" then
143                new[k] = mult_table(v,scale)
144             elseif type(v) == "number" then
145                new[k] = round(v*scale)
146             else
147                new[k] = v
148             end
149          end
150          return new
151       else return nil end
152    end
153    
154    update_jfm_cache = function (j,sz)
155       if metrics[j].size_cache[sz] then return end
156       local t = {}
157       metrics[j].size_cache[sz] = t
158       t.chars = metrics[j].chars
159       t.char_type = mult_table(metrics[j].char_type, sz)
160       for i,v in pairs(t.char_type) do
161          v.align = (v.align=='left') and 0 or 
162             ((v.align=='right') and 1 or 0.5)
163          if type(i) == 'number' then -- char_type
164             for k,w in pairs(v.glue) do
165                local h = node_new(id_glue_spec)
166 mem_leak_gs = mem_leak_gs+1
167                v[k] = {true, h, (w[5] and w[5]/sz or 0), FROM_JFM + (w[4] and w[4]/sz or 0)}
168                setfield(h, 'width', w[1])
169                setfield(h, 'stretch', w[2])
170                setfield(h, 'shrink', w[3])
171                setfield(h, 'stretch_order', 0)
172                setfield(h, 'shrink_order', 0)
173             end
174             for k,w in pairs(v.kern) do
175                local g = node_new(id_kern)
176 mem_leak_kern = mem_leak_kern +1
177                setfield(g, 'kern', w[1])
178                setfield(g, 'subtype', 1)
179                set_attr(g, attr_icflag, FROM_JFM)
180                v[k] = {false, g, w[2]/sz}
181             end
182          end
183          v.glue, v.kern = nil, nil
184       end
185       t.kanjiskip = mult_table(metrics[j].kanjiskip, sz)
186       t.xkanjiskip = mult_table(metrics[j].xkanjiskip,sz)
187       t.zw = round(metrics[j].zw*sz)
188       t.zh = round(metrics[j].zh*sz)
189    end
190 end
191
192 luatexbase.create_callback("luatexja.find_char_class", "data", 
193                            function (arg, fmtable, char)
194                               return 0
195                            end)
196
197 function find_char_class(c,m)
198 -- c: character code, m: 
199    if not m then return 0 end
200    return m.chars[c] or 
201       luatexbase.call_callback("luatexja.find_char_class", 0, m, c)
202 end
203
204
205 ------------------------------------------------------------------------
206 -- LOADING JAPANESE FONTS
207 ------------------------------------------------------------------------
208
209 do
210    local cstemp
211    local global_flag -- true if \globaljfont, false if \jfont
212    local function load_jfont_metric()
213       if jfm_file_name=='' then 
214          ltjb.package_error('luatexja',
215                             'no JFM specified',
216                             'To load and define a Japanese font, a JFM must be specified.'..
217                             "The JFM 'ujis' will be  used for now.")
218          jfm_file_name='ujis'
219       end
220       for j,v in ipairs(metrics) do 
221          if v.name==jfm_file_name then return j end
222       end
223       luatexja.load_lua('jfm-' .. jfm_file_name .. '.lua')
224       if defjfm_res then
225          defjfm_res.name = jfm_file_name
226          table.insert(metrics, defjfm_res)
227          return #metrics
228       else 
229          return nil
230       end
231    end
232
233 -- EXT
234    function jfontdefX(g)
235       local t = token.get_next()
236       cstemp=token.csname_name(t)
237       global_flag = g and '\\global' or ''
238       tex.sprint(cat_lp, '\\expandafter\\font\\csname ' .. cstemp .. '\\endcsname')
239    end
240    
241    luatexbase.create_callback("luatexja.define_jfont", "data", function (ft, fn) return ft end)
242
243 -- EXT
244    function jfontdefY() -- for horizontal font
245       local j = load_jfont_metric()
246       local fn = font.id(cstemp)
247       local f = font_getfont(fn)
248       if not j then 
249          ltjb.package_error('luatexja',
250                             "bad JFM `" .. jfm_file_name .. "'",
251                             'The JFM file you specified is not valid JFM file.\n'..
252                                'So defining Japanese font is cancelled.')
253          tex.sprint(cat_lp, global_flag .. '\\expandafter\\let\\csname ' ..cstemp 
254                        .. '\\endcsname=\\relax')
255          return 
256       end
257       update_jfm_cache(j, f.size)
258       --print('MEMORY LEAK (acc): ', mem_leak_glue, mem_leak_gs, mem_leak_kern)
259       local sz = metrics[j].size_cache[f.size]
260       local fmtable = { jfm = j, size = f.size, var = jfm_var, 
261                         zw = sz.zw, zh = sz.zh, 
262                         chars = sz.chars, char_type = sz.char_type,
263                         kanjiskip = sz.kanjiskip, xkanjiskip = sz.xkanjiskip, 
264       }
265       
266       fmtable = luatexbase.call_callback("luatexja.define_jfont", fmtable, fn)
267       font_metric_table[fn]=fmtable
268       tex.sprint(cat_lp, global_flag .. '\\protected\\expandafter\\def\\csname ' 
269                     .. cstemp  .. '\\endcsname{\\ltj@curjfnt=' .. fn .. '\\relax}')
270    end
271 end
272
273 do
274    -- PUBLIC function
275    function get_zw() 
276       local a = font_metric_table[tex.attribute[attr_curjfnt]]
277       return a and a.zw or 0
278    end
279    function get_zh() 
280       local a = font_metric_table[tex.attribute[attr_curjfnt]]
281       return a and a.zw or 0
282    end
283 end
284
285 do
286    -- extract jfm_file_name and jfm_var
287    local function extract_metric(name)
288       local basename=name
289       local tmp = utf.sub(basename, 1, 5)
290       jfm_file_name = ''; jfm_var = ''
291       if tmp == 'file:' or tmp == 'name:' or tmp == 'psft:' then
292          basename = utf.sub(basename, 6)
293       end
294       local p = utf.find(basename, ":")
295       if p then 
296          basename = utf.sub(basename, p+1)
297       else return 
298       end
299       -- now basename contains 'features' only.
300       p=1
301       while p do
302          local q = utf.find(basename, ";", p+1) or utf.len(basename)+1
303          if utf.sub(basename, p, p+3)=='jfm=' and q>p+4 then
304             jfm_file_name = utf.sub(basename, p+4, q-1)
305          elseif utf.sub(basename, p, p+6)=='jfmvar=' and q>p+6 then
306             jfm_var = utf.sub(basename, p+7, q-1)
307          end
308          if utf.len(basename)+1==q then p = nil else p = q + 1 end
309       end
310       return
311    end
312    
313    -- replace fonts.define.read()
314    function font_callback(name, size, id, fallback)
315       extract_metric(name)
316       -- In the present imple., we don't remove "jfm=..." from name.
317       return fallback(name, size, id)
318    end
319 end
320
321 ------------------------------------------------------------------------
322 -- LATEX INTERFACE
323 ------------------------------------------------------------------------
324 do
325    -- these function are called from ltj-latex.sty
326    local kyenc_list, ktenc_list = {}, {}
327    function add_kyenc_list(enc) kyenc_list[enc] = 'true ' end
328    function add_ktenc_list(enc) ktenc_list[enc] = 'true ' end
329    function is_kyenc(enc)
330       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
331    end
332    function is_kyenc(enc) 
333       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
334    end
335    function is_kenc(enc) 
336       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
337                  .. (kyenc_list[enc] or ktenc_list[enc] or 'false '))
338    end
339
340    local kfam_list, Nkfam_list = {}, {}
341    function add_kfam_list(enc, fam)
342       if not kfam_list[enc] then kfam_list[enc] = {} end
343       kfam_list[enc][fam] = 'true '
344    end
345    function add_Nkfam_list(enc, fam)
346       if not Nkfam_list[enc] then Nkfam_list[enc] = {} end
347       Nkfam_list[enc][fam] = 'true '
348    end
349    function is_kfam(enc, fam)
350       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
351                  .. (kfam_list[enc] and kfam_list[enc][fam] or 'false ')) end
352    function is_Nkfam(enc, fam)
353       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
354                  .. (Nkfam_list[enc] and Nkfam_list[enc][fam] or 'false ')) end
355
356    local ffam_list, Nffam_list = {}, {}
357    function add_ffam_list(enc, fam)
358       if not ffam_list[enc] then ffam_list[enc] = {} end
359       ffam_list[enc][fam] = 'true '
360    end
361    function add_Nffam_list(enc, fam)
362       if not Nffam_list[enc] then Nffam_list[enc] = {} end
363       Nffam_list[enc][fam] = 'true '
364    end
365    function is_ffam(enc, fam)
366       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
367                  .. (ffam_list[enc] and ffam_list[enc][fam] or 'false ')) end
368    function is_Nffam(enc, fam)
369       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
370                  .. (Nffam_list[enc] and Nffam_list[enc][fam] or 'false ')) end
371 end
372 ------------------------------------------------------------------------
373 -- ALTERNATE FONTS
374 ------------------------------------------------------------------------
375 alt_font_table = {}
376 local alt_font_table = alt_font_table
377 local attr_curaltfnt = {}
378 local ucs_out = 0x110000
379
380 ------ for TeX interface
381 -- EXT
382 function set_alt_font(b,e,ind,bfnt)
383    -- ind: 新フォント, bfnt: 基底フォント
384    if b>e then b, e = e, b end
385    if b*e<=0 then
386       ltjb.package_eror('luatexja',
387                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
388                            'I take the intersection with [0x80, 0x10ffff].')
389       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
390    elseif e<0 then -- b<e<0
391       -- do nothing
392    elseif b<0x80 or e>=ucs_out then
393       ltjb.package_warning('luatexja',
394                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
395                               'I take the intersection with [0x80, 0x10ffff].')
396       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
397    end
398    if not alt_font_table[bfnt] then alt_font_table[bfnt]={} end
399    local t = alt_font_table[bfnt]
400    local ac = font_getfont(ind).characters
401    if bfnt==ind then ind = nil end -- ind == bfnt の場合はテーブルから削除
402    if e>=0 then -- character range
403       for i=b, e do
404          if ac[i]then  t[i]=ind end
405       end
406    else
407       b, e = -e, -b
408       local tx = font_metric_table[bfnt].chars
409       for i,v in pairs(tx) do
410          if b<=v and v<=e and ac[i] then t[i]=ind end
411       end
412    end
413 end
414
415 -- EXT
416 function clear_alt_font(bfnt)
417    if alt_font_table[bfnt] then 
418       local t = alt_font_table[bfnt]
419       for i,_ in pairs(t) do t[i]=nil; end
420    end
421 end
422
423 ------ used in ltjp.suppress_hyphenate_ja callback
424 function replace_altfont(pf, pc)
425    local a = alt_font_table[pf]
426    return a and a[pc] or pf
427 end
428
429 ------ for LaTeX interface
430
431 local alt_font_table_latex = {}
432
433 -- EXT
434 function clear_alt_font_latex(bbase)
435    local t = alt_font_table_latex[bbase]
436    if t then
437       for j,v in pairs(t) do t[j] = nil end 
438    end
439 end
440
441 -- EXT
442 function set_alt_font_latex(b,e,ind,bbase)
443    -- ind: Alt font の enc/fam/ser/shape, bbase: 基底フォントの enc/fam/ser/shape
444    if b>e then b, e = e, b end
445    if b*e<=0 then
446       ltjb.package_eror('luatexja',
447                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
448                            'I take the intersection with [0x80, 0x10ffff].')
449       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
450    elseif e<0 then -- b<e<0
451       -- do nothing
452    elseif b<0x80 or e>=ucs_out then
453       ltjb.package_warning('luatexja',
454                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
455                               'I take the intersection with [0x80, 0x10ffff].')
456       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
457    end
458
459    if not alt_font_table_latex[bbase] then alt_font_table_latex[bbase]={} end
460    local t = alt_font_table_latex[bbase]
461    if not t[ind] then t[ind] = {} end
462    for i=b, e do
463       for j,v in pairs(t) do
464          if v[i] then -- remove old entry
465             if j~=ind then v[i]=nil end; break
466          end
467       end
468       t[ind][i]=true
469    end
470    -- remove the empty tables
471    for j,v in pairs(t) do
472       local flag_clear = true
473       for k,_ in pairs(v) do flag_clear = false; break end
474       if flag_clear then t[j]=nil end
475    end
476    if ind==bbase  then t[bbase] = nil end
477 end
478
479 -- ここから先は 新 \selectfont の内部でしか実行されない
480 do
481    local alt_font_base, alt_font_base_num
482    local aftl_base
483    -- EXT
484    function does_alt_set(bbase)
485       aftl_base = alt_font_table_latex[bbase]
486       tex.sprint(cat_lp, '\\if' .. (aftl_base and 'true' or 'false'))
487    end
488    -- EXT
489    function print_aftl_address()
490       tex.sprint(cat_lp, ';ltjaltfont' .. tostring(aftl_base):sub(8))
491    end
492
493 -- EXT
494    function output_alt_font_cmd(bbase)
495       alt_font_base = bbase
496       alt_font_base_num = tex.getattribute(attr_curjfnt)
497       local t = alt_font_table[alt_font_base_num]
498       if t then 
499          for i,_ in pairs(t) do t[i]=nil end
500       end
501       t = alt_font_table_latex[bbase]
502       if t then
503          for i,_ in pairs(t) do
504             tex.sprint(cat_lp, '\\ltj@pickup@altfont@aux{' .. i .. '}')
505          end
506       end
507    end
508
509 -- EXT
510    function pickup_alt_font_a(size_str)
511       local t = alt_font_table_latex[alt_font_base]
512       if t then
513          for i,v in pairs(t) do
514             tex.sprint(cat_lp, '\\expandafter\\ltj@pickup@altfont@copy'
515                           .. '\\csname ' .. i .. '/' .. size_str .. '\\endcsname{' .. i .. '}')
516          end
517       end
518    end 
519
520    local function pickup_alt_font_class(class, afnt_num, afnt_chars)
521       local t  = alt_font_table[alt_font_base_num] 
522       local tx = font_metric_table[alt_font_base_num].chars
523       for i,v in pairs(tx) do
524          if v==class and afnt_chars[i] then t[i]=afnt_num end
525       end
526    end
527
528 -- EXT
529    function pickup_alt_font_b(afnt_num, afnt_base)
530       local t = alt_font_table[alt_font_base_num]
531       local ac = font_getfont(afnt_num).characters
532       if not t then t = {}; alt_font_table[alt_font_base_num] = t end
533       for i,v in pairs(alt_font_table_latex[alt_font_base]) do
534          if i == afnt_base then
535             for j,_ in pairs(v) do
536                if j>=0 then 
537                   if ac[j] then t[j]=afnt_num end
538                else  -- -n (n>=1) means that the character class n,
539                      -- which is defined in the JFM 
540                   pickup_alt_font_class(-j, afnt_num, ac) 
541                end
542             end
543             return
544          end
545       end
546    end
547
548 end
549
550
551 ------------------------------------------------------------------------
552 -- MISC
553 ------------------------------------------------------------------------
554
555 local is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char_direct
556 -- EXT: italic correction
557 function append_italic()
558    local p = to_direct(tex.nest[tex.nest.ptr].tail)
559    if p and getid(p)==id_glyph then
560       local f = getfont(p)
561       local g = node_new(id_kern)
562       setfield(g, 'subtype', 1)
563       set_attr(g, attr_icflag, ITALIC)
564       if is_ucs_in_japanese_char(p) then
565          f = has_attr(p, attr_curjfnt)
566          local j = font_metric_table[f]
567          setfield(g, 'kern', j.char_type[find_char_class(getchar(p), j)].italic)
568       else
569          local h = font_getfont(f)
570          if h then
571             setfield(g, 'kern', h.characters[getchar(p)].italic)
572          else
573             tex.attribute[attr_icflag] = 0
574             return node_free(g)
575          end
576       end
577       node_write(g)
578       tex.attribute[attr_icflag] = 0
579    end
580 end