OSDN Git Service

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