OSDN Git Service

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