OSDN Git Service

Merge branch 'master' into kitagawa_cid
[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       -- shared
175       k.shared = {
176          otfdata = { 
177             cidinfo= k.cidinfo, verbose = false, 
178             shared = { featuredata = {}, }, 
179             luatex = { features = {}, defaultwidth=1000, sequences = {  }, },
180          },
181          dynamics = {}, features = {}, processes = {}, 
182       }
183       k.descriptions = {}
184
185       -- Save
186       local savepath  = path.localdir .. '/luatexja/'
187       if not lfs.isdir(savepath) then
188          dir.mkdirs(savepath)
189       end
190       savepath = file.join(savepath, "ltj-cid-auto-" 
191                            .. string.lower(cid_name)  .. ".lua")
192       if file.iswritable(savepath) then
193          k.characters[46].width = math.floor(655360/14);
194          -- Standard fonts are ``seriffed''. 
195          table.tofile(savepath, k,'return', false, true, false )
196       else 
197          ltjb.package_warning('luatexja', 
198                               'failed to save informations of non-embedded 2-byte fonts', '')
199       end
200    end
201 end
202 local make_cid_font = make_cid_font
203
204 -- 
205 local function read_cid_font()
206    -- local v = "ltj-cid-" .. string.lower(cid_name) .. ".lua"
207    local v = "ltj-cid-auto-" .. string.lower(cid_name) .. ".lua"
208    local localpath  = file.join(path.localdir, v)
209    local systempath = file.join(path.systemdir, v)
210    local kpsefound  = kpse.find_file(v)
211    if kpsefound and file.isreadable(kpsefound) then
212       cidfont_data[cid_name] = require(kpsefound)
213       cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
214    elseif file.isreadable(localpath)  then
215       cidfont_data[cid_name] = require(localpath)
216       cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
217    elseif file.isreadable(systempath) then
218       cidfont_data[cid_name] = require(systempath)
219       cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
220    end
221    -- Now we must create the virtual metrics from CMap.
222    ltjb.package_info('luatexja', 
223                         'I try to generate informations of non-embedded 2-byte fonts...', '')
224    make_cid_font()
225
226    if cidfont_data[cid_name] then
227       for i,v in pairs(cidfont_data[cid_name].characters) do
228          if not v.width then v.width = 655360 end
229          v.height, v.depth = 576716.8, 78643.2 -- optimized for jfm-ujis.lua
230       end
231    end
232 end
233
234 -- High-level
235 local function mk_rml(name, size, id)
236    local specification = fonts.define.analyze(name,size)
237    specification = fonts.define.specify[':'](specification)
238    local features = specification.features.normal
239
240    local fontdata = {}
241    local cachedata = {}
242    local s = cidfont_data[cid_name]
243    for k, v in pairs(s) do
244       fontdata[k] = v
245       cachedata[k] = v
246    end
247    fontdata.characters = nil
248    cachedata.characters = nil
249    fontdata.unicodes = nil
250    fontdata.shared = nil
251    cachedata.shared = nil
252    if s.shared then
253       cachedata.shared = {}
254       local shared = cachedata.shared
255       for k, v in pairs(s.shared) do
256          shared[k] = v
257       end
258       
259       shared.set_dynamics = fonts.otf.set_dynamics 
260       shared.processes, shared.features = fonts.otf.set_features(cachedata,fonts.define.check(features,fonts.otf.features.default))
261    end
262
263    -- characters & scaling
264    if size < 0 then size = -size * 655.36 end
265    local scale = size / 655360
266    local def_height =  0.88 * size -- character's default height (optimized for jfm-ujis.lua)
267    local def_depth =  0.12 * size  -- and depth.
268    if not cache_chars[cid_name][size] then
269       cache_chars[cid_name][size]  = {}
270       for k, v in pairs(cache_chars[cid_name][655360]) do
271          cache_chars[cid_name][size][k] = { 
272             index = v.index, width = v.width * scale, 
273             height = def_height, depth = def_depth, tounicode = v.tounicode,
274          }
275       end
276    end
277    fontdata.characters = cache_chars[cid_name][size]
278    cachedata.characters = cache_chars[cid_name][size]
279
280    local parameters = {}
281    for k, v in pairs(s.parameters) do
282       parameters[k] = v * scale
283    end
284    fontdata.parameters = parameters;                cachedata.parameters = parameters
285    fontdata.ascender = fontdata.ascender * scale;   cachedata.ascender = fontdata.ascender
286    fontdata.descender = fontdata.descender * scale; cachedata.descender = fontdata.descender
287    fontdata.factor = fontdata.factor * scale;       cachedata.factor = fontdata.factor
288    fontdata.hfactor = fontdata.hfactor * scale;     cachedata.hfactor = fontdata.hfactor
289    fontdata.vfactor = fontdata.vfactor * scale;     cachedata.vfactor = fontdata.vfactor
290    fontdata.size = size;                            cachedata.size = size
291
292    -- no embedding
293    local var = ''
294    if features.slant then 
295       fontdata.slant = features.slant*1000;         cachedata.slant = fontdata.slant
296       var = var .. 's' .. tostring(features.slant)
297    end
298    if features.extend then 
299       fontdata.extend = features.extend*1000;       cachedata.extend = fontdata.extend
300        var = var .. 'x' .. tostring(features.extend)
301   end
302    fontdata.name = specification.name .. size .. var; cachedata.name = fontdata.name
303    fontdata.fullname = specification.name .. var; cachedata.fullname = fontdata.fullname
304    fontdata.psname = specification.name; cachedata.psname = fontdata.psname
305    fonts.ids[id] = cachedata
306
307    return fontdata
308 end
309
310 local dr_orig = fonts.define.read
311 function fonts.define.read(name, size, id)
312    local p = utf.find(name, ":") or utf.len(name)+1
313    if utf.sub(name, 1, p-1) == 'psft' then
314       local s = "Adobe-Japan1-6"
315       local basename = utf.sub(name,p+1)
316       local p = utf.find(basename, ":")
317       if p then 
318          local xname = utf.sub(basename, p+1)
319          p = 1
320          while p do
321             local q = utf.find(xname, ";", p+1) or utf.len(xname)+1
322             if utf.sub(xname, p, p+3)=='cid=' and q>p+4 then
323                s = utf.sub(xname, p+4, q-1)
324             end
325             if utf.len(xname)+1==q then p = nil else p = q + 1 end
326          end
327       end
328       cid_reg, cid_order = string.match(s, "^(.-)%-(.-)%-(%d-)$")
329       if not cid_reg then 
330          cid_reg, cid_order = string.match(s, "^(.-)%-(.-)$")
331       end
332       cid_name = cid_reg .. '-' .. cid_order
333       if not cidfont_data[cid_name] then 
334          read_cid_font()
335          if not cidfont_data[cid_name] then 
336             ltjb.package_error('luatexja',
337                                "bad cid key `" .. s .. "'",
338                                "I couldn't find any non-embedded font information for the CID\n" ..
339                                   '`' .. s .. "'. For now, I'll use `Adobe-Japan1-6'.\n"..
340                                   'Please contact the LuaTeX-ja project team.')
341             cid_name = "Adobe-Japan1"
342          end
343       end
344       return mk_rml(basename, size, id)
345    else 
346       return dr_orig(name, size, id)
347    end
348 end
349
350 cid_reg, cid_order, cid_name = 'Adobe', 'Japan1', 'Adobe-Japan1'
351 read_cid_font()