OSDN Git Service

Fix #38871
[luatex-ja/luatexja.git] / src / ltj-rmlgbm.lua
1 --
2 -- luatexja/ltj-rmlgbm.lua
3 --
4 luatexja.load_module('base');      local ltjb = luatexja.base
5
6 local cidfont_data = {}
7 local cache_chars = {}
8 local cache_ver = 7
9 local identifiers = fonts.hashes.identifiers
10
11 local cid_reg, cid_order, cid_supp, cid_name
12 local cid_replace = {
13    ["Adobe-Japan1"] = {"UniJIS2004-UTF32", 23057, 6,
14                        function (i)
15                           if (231<=i and i<=632) or (8718<=i and i<=8719)
16                              or (12063<=i and i<=12087) then
17                              return 327680 -- 655360/2
18                           elseif 9758<=i and i<=9778 then
19                              return 218453 -- 655360/3
20                           elseif 9738<=i and i<=9757 then
21                              return 163840 -- 655360/4
22                           end
23                        end},
24                        -- 基本的には JIS X 0213:2004 に沿ったマッピング
25    ["Adobe-Korea1"] = {"UniKS-UTF32",  18351, 2,
26                        function (i)
27                           if 8094<=i and i<=8100 then
28                              return 327680 -- 655360/2
29                           end
30                        end},
31    ["Adobe-GB1"]    = {"UniGB-UTF32",  30283, 5,
32                        function (i)
33                           if (814<=i and i<=939) or (i==7716)
34                              or (22355<=i and i<=22357) then
35                              return 327680 -- 655360/2
36                           end
37                        end},
38    ["Adobe-CNS1"]   = {"UniCNS-UTF32", 19155, 6,
39                        function (i)
40                           if (13648<=i and i<=13742) or (i==17603) then
41                              return 327680 -- 655360/2
42                           end
43                        end},
44 }
45
46 -- reading CID maps
47 local make_cid_font
48 do
49    local line, fh -- line, file handler
50    local tt,cidm -- characters, cid->(Unicode)
51
52    local function load_cid_char(cid_dec, mke)
53       local cid, ucs, ucsa
54       line = fh:read("*l")
55       while line do
56          if string.find(line, "end...?char") then
57             line = fh:read("*l"); return
58          else -- WMA l is in the form "<%x+>%s%d+"
59             ucs, cid = string.match(line, "<(%x+)>%s+<?(%x+)>?")
60             cid = cid_dec(cid); ucs = tonumber(ucs, 16);
61             if not tt[ucs]  then
62                tt[ucs] = mke(cid); cidm[cid]=ucs
63             end
64          end
65          line = fh:read("*l")
66       end
67    end
68
69    local function load_cid_range(inc, cid_dec, mke)
70       local bucs, eucs, cid
71       line = fh:read("*l")
72       while line do
73         if string.find(line, "end...?range") then
74             line = fh:read("*l"); return
75          else -- WMA l is in the form "<%x+>%s+<%x+>"
76             bucs, eucs, cid = string.match(line, "<(%x+)>%s+<(%x+)>%s+<?(%x+)>?")
77             cid = cid_dec(cid);
78             bucs = tonumber(bucs, 16); eucs = tonumber(eucs, 16)
79             for ucs = bucs, eucs do
80                if not tt[ucs]  then
81                   tt[ucs] = mke(cid); cidm[cid]=ucs
82                end
83                cid = inc(cid)
84             end
85          end
86          line = fh:read("*l")
87       end
88    end
89
90    local function open_cmap_file(name, inc, cid_dec, mke)
91       fh = io.open(kpse.find_file(name, 'cmap files'), "r")
92       line = fh:read("*l")
93       while line do
94          if string.find(line, "%x+%s+begin...?char") then
95             load_cid_char(cid_dec, mke)
96          elseif string.find(line, "%x+%s+begin...?range") then
97             load_cid_range(inc, cid_dec, mke)
98          else
99             line = fh:read("*l")
100          end
101       end
102       fh:close();
103    end
104
105    local function increment(a) return a+1 end
106    local function entry(a)
107       return {index = a}
108    end
109    make_cid_font = function ()
110       local kx = cid_replace[cid_name]
111       if not kx then return end
112       local k = {
113          cidinfo = { ordering=cid_order, registry=cid_reg, supplement=kx[3] },
114          encodingbytes = 2, extend=1000, format = 'opentype',
115          direction = 0, characters = {}, parameters = {
116             ascender = 655360*0.88,
117             descender = 655360*0.12,
118          },
119          embedding = "no", cache = "yes", factor = 0, hfactor = 0, vfactor = 0,
120          tounicode = 1,
121          properties = { language = "dflt", script = "dflt" },
122       }
123       cidfont_data[cid_name] = k
124
125       -- CID => Unicode 符号空間
126       local tth, cidmo = {}, {}
127       tt, cidm = tth, cidmo
128       for i = 0,kx[2] do cidm[i] = -1 end
129       open_cmap_file(kx[1] .. "-H", increment, tonumber, entry)
130       k.characters = tth
131
132       -- Unicode にマップされなかった文字の処理
133       -- これらは TrueType フォントを使って表示するときはおかしくなる
134       local ttu, pricode = {}, 0xF0000
135       for i,v in ipairs(cidmo) do
136          if v==-1 then
137             tth[pricode], cidmo[i], pricode
138                = { index = i }, pricode, pricode+1;
139          end
140          ttu[cid_order .. '.' .. i] = cidmo[i]
141       end
142
143       -- shared
144       k.shared = {
145          otfdata = {
146             cidinfo= k.cidinfo, verbose = false,
147             shared = { featuredata = {}, },
148          },
149          dynamics = {}, features = {}, processes = {},
150          --rawdata = { descriptions = {} },
151       }
152       k.resources = { 
153          unicodes = ttu, 
154          features = { dummy={dummy={dflt=true}} }
155       }
156       k.descriptions = {}
157       cache_chars[cid_name]  = { [655360] = k.characters }
158
159       -- 縦書用字形
160       tt, cidm = {}, {}
161       local ttv = {}; k.shared.ltj_vert_table = ttv
162       for i = 0,kx[2] do cidm[i] = -1 end
163       open_cmap_file(kx[1] .. "-V", increment, tonumber, entry)
164       for i,v in pairs(tt) do
165          ttv[i] =  cidmo[v.index]
166       end
167
168       -- tounicode エントリ
169       local cidp = {nil, nil}; tt, ttu, cidm = {}, {}, {}
170       open_cmap_file(cid_name .. "-UCS2",
171                      function(a)
172                         a[2] = a[2] +1 ; return a
173                      end,
174                      function(a)
175                         cidp[1] = string.upper(string.sub(a,1,string.len(a)-4))
176                         cidp[2] = tonumber(string.sub(a,-4),16)
177                         return cidp
178                      end,
179                      function(a) return a[1] ..string.format('%04X',a[2])  end)
180       -- tt は cid -> tounicode になっているので cidm -> tounicode に変換
181       local kxf = kx[4]
182       for i,v in ipairs(cidmo) do
183          k.characters[v].width = kxf(i)
184          if v>=0xF0000 then
185             k.characters[v].tounicode = tt[i]
186          end
187       end
188
189       -- Save
190       k.characters[46].width = math.floor(655360/14);
191       ltjb.save_cache( "ltj-cid-auto-" .. string.lower(cid_name),
192                        {
193                           version = cache_ver,
194                           k,
195                        })
196    end
197 end
198
199 --
200 local cidf_vert_processor
201 do
202    local traverse_id = node.traverse_id
203    local id_glyph = node.id('glyph')
204    cidf_vert_processor = {
205       function (head, fnum)
206          local fontdata = identifiers[fnum]
207          if luatexja.jfont.font_metric_table[fnum].vert_activated then
208             local vt = fontdata.shared.ltj_vert_table
209             for n in traverse_id(id_glyph, head) do
210                if n.font==fnum then
211                   n.char = vt[n.char] or n.char
212                end
213             end
214             return head, false
215          end
216       end
217    }
218 end
219
220 local function cid_cache_outdated(t) return t.version~=cache_ver end
221 local function read_cid_font()
222    local dat = ltjb.load_cache("ltj-cid-auto-" .. string.lower(cid_name),
223                                cid_cache_outdated )
224    if dat then
225       cidfont_data[cid_name] = dat[1]
226       cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
227    else
228       -- Now we must create the virtual metrics from CMap.
229       make_cid_font()
230    end
231    if cidfont_data[cid_name] then
232       cidfont_data[cid_name].shared.processes = cidf_vert_processor
233       for i,v in pairs(cidfont_data[cid_name].characters) do
234          if not v.width then v.width = 655360 end
235          v.height, v.depth = 576716.8, 78643.2 -- optimized for jfm-ujis.lua
236       end
237       return cidfont_data[cid_name]
238    else
239       return nil
240    end
241 end
242
243 -- High-level
244 local function prepare_cid_font(reg, ord)
245    cid_reg, cid_order, cid_name, cid_supp = reg, ord, reg .. '-' .. ord
246    return cidfont_data[cid_name] or read_cid_font()
247 end
248
249
250 local definers = fonts.definers
251 local function mk_rml(name, size, id)
252    local specification = definers.analyze(name,size)
253    --specification = definers.resolve(specification) (not needed)
254    specification.detail = specification.detail or ''
255
256    local fontdata = {}
257    local cachedata = {}
258    local s = cidfont_data[cid_name]
259    luatexja.rmlgbm.vert_addfunc(id)
260    for k, v in pairs(s) do
261       fontdata[k] = v
262       cachedata[k] = v
263    end
264    fontdata.characters = nil
265    cachedata.characters = nil
266    fontdata.shared = nil
267    cachedata.shared = nil
268    if s.shared then
269       cachedata.shared = {}
270       local shared = cachedata.shared
271       for k, v in pairs(s.shared) do
272          shared[k] = v
273       end
274    end
275
276    -- characters & scaling
277    if size < 0 then size = -size * 655.36 end
278    local scale = size / 655360
279
280    do
281       local def_height =  0.88 * size
282       -- character's default height (optimized for jfm-ujis.lua)
283       local def_depth =  0.12 * size  -- and depth.
284       if not cache_chars[cid_name][size] then
285          cache_chars[cid_name][size]  = {}
286          for k, v in pairs(cache_chars[cid_name][655360]) do
287             cache_chars[cid_name][size][k] = {
288                index = v.index, width = v.width * scale,
289                height = def_height, depth = def_depth, tounicode = v.tounicode,
290             }
291          end
292       end
293       fontdata.characters = cache_chars[cid_name][size]
294       cachedata.characters = cache_chars[cid_name][size]
295    end
296
297    -- other parameters
298    do
299       local parameters = {}
300       for k, v in pairs(s.parameters) do
301          parameters[k] = v * scale
302       end
303       fontdata.parameters  = parameters
304       fontdata.size        = size
305       fontdata.resources   = s.resources
306       cachedata.parameters = parameters
307       cachedata.size       = size
308       cachedata.resources  = s.resources
309    end
310
311    -- no embedding
312    local var = ''
313    local s = string.match(specification.detail, 'slant=([+-]*%d*%.?%d)')
314    if s and e~=0  then
315       s = s * 1000
316       var, fontdata.slant  = var .. 's' .. tostring(s), s
317    end
318    local e = string.match(specification.detail, 'extend=([+-]*%d*%.?%d)')
319    if e and e~=1  then
320       e = e * 1000
321       var, fontdata.extend  = var .. 'x' .. tostring(e), e
322    end
323    fontdata.name = specification.name .. size .. var; cachedata.name = fontdata.name
324    fontdata.fullname = specification.name .. var; cachedata.fullname = fontdata.fullname
325    fontdata.psname = specification.name; cachedata.psname = fontdata.psname
326    identifiers[id] = cachedata
327
328    return fontdata
329 end
330
331 local function font_callback(name, size, id, fallback)
332    if name:sub(1,1)=="{" and name:sub(-1)=="}" then name = name:sub(2,-2) end
333    local p = name:find(":") or 0
334    if name:sub(1, p-1) == 'psft' then
335       local s = "Adobe-Japan1-6"
336       local basename = name:sub(p+1)
337       local p = basename:find(":")
338       local q = basename:find("/[BI][BI]?")
339       if q and p and q<=p then
340          basename = basename:gsub('/[BI][BI]?', '', 1)
341          p = basename:find(":")
342       end
343       if p then
344          local xname = basename:sub(p+1)
345          p = 1
346          while p do
347             local q = xname:find(";", p+1) or xname:len()+1
348             if xname:sub(p, p+3)=='cid=' and q>p+4 then
349                s = xname:sub(p+4, q-1)
350             end
351             if xname:len()+1==q then p = nil else p = q + 1 end
352          end
353       end
354       cid_reg, cid_order = string.match(s, "^(.-)%-(.-)%-(%d-)$")
355       if not cid_reg then
356          cid_reg, cid_order = string.match(s, "^(.-)%-(.-)$")
357       end
358       if not prepare_cid_font(cid_reg, cid_order) then
359          ltjb.package_error('luatexja',
360                             "bad cid key `" .. s .. "'",
361                             "I couldn't find any non-embedded font information for the CID\n" ..
362                                '`' .. s .. "'. For now, I'll use `Adobe-Japan1-6'.\n"..
363                                'Please contact the LuaTeX-ja project team.')
364          cid_name = "Adobe-Japan1"
365       end
366       return mk_rml(basename, size, id)
367    else
368       local tfmdata=fallback(name, size, id)
369       if type (tfmdata) == "table" and tfmdata.shared then
370         luatexbase.call_callback("luaotfload.patch_font", tfmdata, name)
371       end
372       return tfmdata
373    end
374 end
375
376 luatexja.rmlgbm = {
377    prepare_cid_font = prepare_cid_font,
378    cidfont_data = cidfont_data,
379    font_callback = font_callback,
380    vert_addfunc = function () end, -- dummy, set in ltj-direction.lua
381 }
382
383 prepare_cid_font('Adobe', 'Japan1')