OSDN Git Service

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