OSDN Git Service

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