OSDN Git Service

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