OSDN Git Service

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