OSDN Git Service

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