OSDN Git Service

Merge branch 'master' into kitagawa_test
[luatex-ja/luatexja.git] / src / ltj-otf.lua
1 --
2 -- luatexja/ltj-otf.lua
3 --
4 require('unicode')
5 require('lualibs')
6
7 luatexja.load_module('base');      local ltjb = luatexja.base
8 luatexja.load_module('jfont');     local ltjf = luatexja.jfont
9 luatexja.load_module('rmlgbm');    local ltjr = luatexja.rmlgbm
10 luatexja.load_module('charrange'); local ltjc = luatexja.charrange
11
12 local id_glyph = node.id('glyph')
13 local id_whatsit = node.id('whatsit')
14 local sid_user = node.subtype('user_defined')
15
16 local node_new = node.new
17 local node_remove = node.remove
18 local node_next = node.next
19 local node_free = node.free
20 local has_attr = node.has_attribute
21 local set_attr = node.set_attribute
22 local unset_attr = node.unset_attribute
23 local node_insert_after = node.insert_after
24 local identifiers = fonts.hashes.identifiers
25
26 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
27 local attr_yablshift = luatexbase.attributes['ltj@yablshift']
28 local attr_ykblshift = luatexbase.attributes['ltj@ykblshift']
29
30 local ltjf_font_metric_table = ltjf.font_metric_table
31 local ltjf_find_char_class = ltjf.find_char_class
32 local ltjr_cidfont_data = ltjr.cidfont_data
33 local ltjc_is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char
34
35 luatexja.userid_table.OTF = luatexbase.newuserwhatsitid('char_by_cid',  'luatexja')
36 luatexja.userid_table.VSR = luatexbase.newuserwhatsitid('replace_vs',  'luatexja') 
37 local OTF, VSR = luatexja.userid_table.OTF, luatexja.userid_table.VSR
38
39 local function get_ucs_from_rmlgbm(c)
40    local v = ltjr_cidfont_data["Adobe-Japan1"].resources.unicodes["Japan1." .. tostring(c)]
41    if not v then -- AJ1 範囲外
42       return 0
43    elseif v<0xF0000 then -- 素直に Unicode にマップ可能
44       return v
45    else
46       local w = ltjr_cidfont_data["Adobe-Japan1"].characters[v]. tounicode
47       -- must be non-nil!
48       local i = string.len(w)
49       if i==4 then -- UCS2
50          return tonumber(w,16)
51       elseif i==8 then 
52          i,w = tonumber(string.sub(w,1,4),16), tonumber(string.sub(w,-4),16)
53          if (w>=0xD800) and (w<=0xDB7F) and (i>=0xDC00) and (i<=0xDFFF) then -- Surrogate pair
54             return (w-0xD800)*0x400 + (i-0xDC00)
55          else
56             return 0
57          end
58       end
59    end
60 end
61
62 -- Append a whatsit node to the list.
63 -- This whatsit node will be extracted to a glyph_node
64 local function append_jglyph(char)
65    local p = node_new(id_whatsit,sid_user)
66    local v = tex.attribute[attr_curjfnt]
67    p.user_id=OTF; p.type=100; p.value=char
68    set_attr(p, attr_yablshift, tex.attribute[attr_ykblshift])
69    node.write(p)
70 end
71
72 local function cid(key)
73    if key==0 then return append_jglyph(char) end
74    local curjfnt = identifiers[tex.attribute[attr_curjfnt]]
75    if not curjfnt.cidinfo or 
76       curjfnt.cidinfo.ordering ~= "Japan1" and
77       curjfnt.cidinfo.ordering ~= "GB1" and
78       curjfnt.cidinfo.ordering ~= "CNS1" and
79       curjfnt.cidinfo.ordering ~= "Korea1" then
80 --      ltjb.package_warning('luatexja-otf',
81 --                         'Current Japanese font (or other CJK font) "'
82 --                            ..curjfnt.psname..'" is not a CID-Keyed font (Adobe-Japan1 etc.)')
83       return append_jglyph(get_ucs_from_rmlgbm(key))
84    end
85    local char = curjfnt.resources.unicodes[curjfnt.cidinfo.ordering..'.'..tostring(key)]
86    if not char then
87       ltjb.package_warning('luatexja-otf',
88                            'Current Japanese font (or other CJK font) "'
89                               ..curjfnt.psname..'" does not have the specified CID character ('
90                               ..tostring(key)..')', 
91                            'Use a font including the specified CID character.')
92       char = 0
93    end
94    return append_jglyph(char)
95 end
96
97 local function extract(head)
98    local p = head
99    local v
100    while p do
101       if p.id==id_whatsit then
102          if p.subtype==sid_user then
103             local puid = p.user_id
104             if puid==OTF or puid==VSR then
105                local g = node_new(id_glyph)
106                g.subtype = 0; g.char = p.value
107                v = has_attr(p, attr_curjfnt); g.font = v
108                set_attr(g, attr_curjfnt, 
109                         puid==OTF and v or 0)
110                -- VSR yields ALchar
111                v = has_attr(p, attr_yablshift)
112                if v then 
113                   set_attr(g, attr_yablshift, v)
114                else
115                   unset_attr(g, attr_yablshift)
116                end
117                head = node_insert_after(head, p, g)
118                head = node_remove(head, p)
119                node_free(p); p = g
120             end
121          end
122       end
123       p = node_next(p)
124    end
125    return head
126 end
127
128 luatexbase.add_to_callback('hpack_filter', 
129    function (head) return extract(head) end,'ltj.hpack_filter_otf',
130    luatexbase.priority_in_callback('pre_linebreak_filter',
131                                    'ltj.pre_linebreak_filter'))
132 luatexbase.add_to_callback('pre_linebreak_filter', 
133    function (head) return extract(head) end, 'ltj.pre_linebreak_filter_otf',
134    luatexbase.priority_in_callback('pre_linebreak_filter',
135                                    'ltj.pre_linebreak_filter'))
136
137
138 -- additional callbacks
139 -- 以下は,LuaTeX-ja に用意された callback のサンプルになっている.
140 --   JFM の文字クラスの指定の所で,"AJ1-xxx" 形式での指定を可能とした.
141 --   これらの文字指定は,和文フォント定義ごとに,それぞれのフォントの
142 --   CID <-> グリフ 対応状況による変換テーブルが用意される.
143
144 -- 和文フォント読み込み時に,CID -> unicode 対応をとっておく.
145 local function cid_to_char(fmtable, fn)
146    local fi = identifiers[fn]
147    if fi.cidinfo and fi.cidinfo.ordering == "Japan1" then
148       fmtable.cid_char_type = {}
149       for i, v in pairs(fmtable.chars) do
150          local j = string.match(i, "^AJ1%-([0-9]*)")
151          if j then
152             j = tonumber(fi.resources.unicodes['Japan1.'..tostring(j)])
153             if j then
154                fmtable.cid_char_type[j] = v 
155             end
156          end
157       end
158    end
159    return fmtable
160 end
161 luatexbase.add_to_callback("luatexja.define_jfont", 
162                            cid_to_char, "ltj.otf.define_jfont", 1)
163 --  既に読み込まれているフォントに対しても,同じことをやらないといけない
164 for fn, v in pairs(ltjf_font_metric_table) do
165    ltjf_font_metric_table[fn] = cid_to_char(v, fn)
166 end
167
168
169 local function cid_set_char_class(arg, fmtable, char)
170    if arg~=0 then return arg
171    elseif fmtable.cid_char_type then
172       return fmtable.cid_char_type[char] or 0
173    else return 0
174    end
175 end
176 luatexbase.add_to_callback("luatexja.find_char_class", 
177                            cid_set_char_class, "ltj.otf.find_char_class", 1)
178
179 -------------------- IVS
180 local font_ivs_table = {} -- key: fontnumber
181 local enable_ivs
182 do
183    local is_ivs_enabled = false
184    local ivs -- temp table
185    local sort = table.sort
186    local uniq_flag
187    local function add_ivs_table(tg, unitable)
188       for gu, gv in pairs(tg) do
189          local ga = gv.altuni
190          if ga then
191             for _,at in pairs(ga) do
192                local bu, vsel = at.unicode, (at.variant or -1)
193                if vsel~=-1 then
194                   if vsel>=0xE0100 then vsel = vsel - 0xE0100 end
195                   if not ivs[bu] then ivs[bu] = {} end
196                   uniq_flag = true
197                   for i,_ in pairs(ivs[bu]) do
198                      if i==vs then uniq_flag = false; break end
199                   end
200                   if uniq_flag then 
201                      ivs[bu][vsel] = unitable[gv.name]
202                   end
203                end
204             end
205          end
206       end
207    end
208    local function make_ivs_table(id, fname)
209       ivs = {}
210       local fl = fontloader.open(fname)
211       local ft = fontloader.to_table(fl)
212       local unicodes = id.resources.unicodes
213       add_ivs_table(ft.glyphs, id.resources.unicodes)
214       if ft.subfonts then
215          for _,v in pairs(ft.subfonts) do
216             add_ivs_table(v.glyphs, id.resources.unicodes)
217          end
218       end
219       fontloader.close(fl)
220       return ivs
221    end
222
223 -- loading and saving
224    local font_ivs_basename = {} -- key: basename
225    local cache_ver = 4
226    local checksum = file.checksum
227
228    local function prepare_ivs_data(n, id)
229       -- test if already loaded
230       if type(id)=='number' then -- sometimes id is an integer
231          font_ivs_table[n] = font_ivs_table[id]; return
232       elseif not id then return
233       end
234       local fname = id.filename
235       local bname = file.basename(fname)
236       if not fname then 
237          font_ivs_table[n] = {}; return
238       elseif font_ivs_basename[bname] then 
239          font_ivs_table[n] = font_ivs_basename[bname]; return
240       end
241       
242       -- if the cache is present, read it
243       local newsum = checksum(fname) -- MD5 checksum of the fontfile
244       local v = "ivs_" .. string.lower(file.nameonly(fname))
245       local dat = ltjb.load_cache(v, 
246          function (t) return (t.version~=cache_ver) or (t.chksum~=newsum) end
247       )
248       -- if the cache is not found or outdated, save the cache
249       if dat then 
250          font_ivs_basename[bname] = dat[1] or {}
251       else
252          dat = make_ivs_table(id, fname)
253          font_ivs_basename[bname] = dat or {}
254          ltjb.save_cache( v,
255                           {
256                              chksum = checksum(fname), 
257                              version = cache_ver,
258                              dat,
259                           })
260       end
261       font_ivs_table[n] = font_ivs_basename[bname]
262    end
263
264 -- 組版時
265    local function ivs_jglyph(char, bp, pf, uid)
266       local p = node_new(id_whatsit,sid_user)
267       p.user_id=uid; p.type=100; p.value=char
268       set_attr(p, attr_curjfnt, pf)
269       set_attr(p, attr_yablshift, has_attr(bp, attr_ykblshift) or 0)
270       return p
271    end
272
273    local function do_ivs_repr(head)
274       local p = head
275       while p do
276          local pid = p.id
277          if pid==id_glyph then
278             local pf = p.font
279             local q = node_next(p) -- the next node of p
280             if q and q.id==id_glyph then
281                local qc = q.char
282                if (qc>=0xFE00 and qc<=0xFE0F) or (qc>=0xE0100 and qc<0xE01F0) then 
283                   -- q is a variation selector
284                   if qc>=0xE0100 then qc = qc - 0xE0100 end
285                   local pt = font_ivs_table[pf]
286                   pt = pt and pt[p.char];  pt = pt and  pt[qc]
287                   head = node_remove(head,q)
288                   if pt then
289                      local np = ivs_jglyph(pt, p, pf,
290                                            (has_attr(p,attr_curjfnt) or 0)==pf and OTF or VSR)
291                      head = node_insert_after(head, p, np) 
292                      head = node_remove(head,p)
293                      p = np
294                   end
295                end
296             end
297          end
298          p = node_next(p)
299       end
300       return head
301    end
302
303    -- font define
304    local function font_callback(name, size, id, fallback)
305       local d = fallback(name, size, id)
306       prepare_ivs_data(id, d)
307       return d
308    end
309
310    enable_ivs = function ()
311       if is_ivs_enabled then
312          ltjb.package_warning('luatexja-otf',
313                               'luatexja.otf.enable_ivs() was already called, so this call is ignored', '')
314       else
315          luatexbase.add_to_callback('hpack_filter', 
316                                     function (head) return do_ivs_repr(head) end,'do_ivs', 1)
317          luatexbase.add_to_callback('pre_linebreak_filter', 
318                                     function (head) return do_ivs_repr(head) end, 'do_ivs', 1)
319          local ivs_callback = function (name, size, id)
320             return font_callback(
321                name, size, id, 
322                function (name, size, id) return luatexja.font_callback(name, size, id) end
323             )
324          end
325          luatexbase.add_to_callback('define_font',ivs_callback,"luatexja.ivs_font_callback", 1)
326          for i=1,font.nextid()-1 do
327             if identifiers[i] then prepare_ivs_data(i, identifiers[i]) end
328          end
329          is_ivs_enabled = true
330       end
331    end
332 end
333
334 luatexja.otf = {
335   append_jglyph = append_jglyph,
336   enable_ivs = enable_ivs,  -- 隠し機能: IVS
337   font_ivs_table = font_ivs_table,
338   cid = cid,
339 }
340
341 -- EOF