OSDN Git Service

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