OSDN Git Service

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