OSDN Git Service

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