OSDN Git Service

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