OSDN Git Service

4bafaf2142cb91c403685fbc55c994457e011828
[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 cidfont_data = {}
16 local cidfont_data = cidfont_data
17 local cache_chars = {}
18 local path           = {
19     localdir  = file.join(kpse.expand_var("$TEXMFVAR"), aux_dir),
20     systemdir = file.join(kpse.expand_var("$TEXMFSYSVAR"), aux_dir),
21 }
22
23 local cid_reg, cid_order, cid_supp, cid_name
24 local taux_dir = 'luatex-cache/luatexja'
25 local cid_replace = {
26    ["Adobe-Japan1"] = {"UniJIS2004-UTF32", 23057, 
27                        function (i)
28                           if (231<=i and i<=632) or (8718<=i and i<=8719) 
29                              or (12063<=i and i<=12087) then
30                              return 327680 -- 655360/2
31                           elseif 9758<=i and i<=9778 then
32                              return 218453 -- 655360/3
33                           elseif 9738<=i and i<=9757 then
34                              return 163840 -- 655360/4
35                           end
36                        end},
37                        -- 基本的には JIS X 0213:2004 に沿ったマッピング
38    ["Adobe-Korea1"] = {"UniKS-UTF32",  18351,
39                        function (i)
40                           if 8094<=i and i<=8100 then 
41                              return 327680 -- 655360/2
42                           end
43                        end},
44    ["Adobe-GB1"]    = {"UniGB-UTF32",  30283,
45                        function (i)
46                           if (814<=i and i<=939) or (i==7716) 
47                              or (22355<=i and i<=22357) then
48                              return 327680 -- 655360/2
49                           end
50                        end},
51    ["Adobe-CNS1"]   = {"UniCNS-UTF32", 19155,
52                        function (i)
53                           if (13648<=i and i<=13742) or (i==17603) then
54                              return 327680 -- 655360/2
55                           end
56                        end},
57 }
58
59 -- reading CID maps
60 do
61    local line, fh -- line, file handler
62    local tt,cidm -- characters, cid->(Unicode)
63
64    local function load_cid_char(cid_dec, mke)
65       local cid, ucs, ucsa
66       line = fh:read("*l")
67       while line do
68          if string.find(line, "end...?char") then 
69             line = fh:read("*l"); return
70          else -- WMA l is in the form "<%x+>%s%d+"
71             ucs, cid = string.match(line, "<(%x+)>%s+<?(%x+)>?")
72             cid = cid_dec(cid); ucs = tonumber(ucs, 16); 
73             if not tt[ucs]  then 
74                tt[ucs] = mke(cid); cidm[cid]=ucs
75             end
76          end
77          line = fh:read("*l")
78       end
79    end
80
81    local function load_cid_range(inc, cid_dec, mke)
82       local bucs, eucs, cid
83       line = fh:read("*l")
84       while line do
85         if string.find(line, "end...?range") then 
86             line = fh:read("*l"); return
87          else -- WMA l is in the form "<%x+>%s+<%x+>"
88             bucs, eucs, cid = string.match(line, "<(%x+)>%s+<(%x+)>%s+<?(%x+)>?")
89             cid = cid_dec(cid); 
90             bucs = tonumber(bucs, 16); eucs = tonumber(eucs, 16)
91             for ucs = bucs, eucs do
92                if not tt[ucs]  then 
93                   tt[ucs] = mke(cid); cidm[cid]=ucs
94                end
95                cid = inc(cid)
96             end
97          end
98          line = fh:read("*l")
99       end
100    end
101
102    local function open_cmap_file(name, inc, cid_dec, mke)
103       fh = io.open(kpse.find_file(name, 'cmap files'), "r")
104       line = fh:read("*l")
105       while line do
106          if string.find(line, "%x+%s+begin...?char") then
107             load_cid_char(cid_dec, mke)
108          elseif string.find(line, "%x+%s+begin...?range") then
109             load_cid_range(inc, cid_dec, mke)
110          else
111             line = fh:read("*l")
112          end
113       end
114       fh:close();  
115    end
116    
117    local function increment(a) return a+1 end
118    local function entry(a)     
119       return {index = a} 
120    end
121    function make_cid_font()
122       local k = {
123          cidinfo = { ordering=cid_order, registry=cid_reg, supplement=cid_supp },
124          encodingbytes = 2, extend=1000, format = 'opentype',
125          direction = 0, characters = {}, parameters = {}, embedding = "no", cache = "yes", 
126          ascender = 0, descender = 0, factor = 0, hfactor = 0, vfactor = 0,
127          tounicode = 1,
128       }
129       local kx = cid_replace[cid_name]
130       cidfont_data[cid_name] = k
131
132       -- CID => Unicode 符号空間
133       -- TODO: vertical fonts?
134       tt, cidm = {}, {}
135       for i = 0,kx[2] do cidm[i] = -1 end
136       open_cmap_file(kx[1] .. "-H", increment, tonumber, entry)
137       k.characters = tt
138
139       -- Unicode にマップされなかった文字の処理
140       -- これらは TrueType フォントを使って表示するときはおかしくなる
141       local ttu, pricode = {}, 0xF0000
142       for i,v in ipairs(cidm) do
143          if v==-1 then 
144             tt[pricode], cidm[i], pricode 
145                = { index = i }, pricode, pricode+1;
146          end
147          ttu[cid_order .. '.' .. i] = cidm[i]
148       end
149       -- shared
150       k.shared = {
151          otfdata = { 
152             cidinfo= k.cidinfo, verbose = false, 
153             shared = { featuredata = {}, }, 
154             luatex = { features = {}, 
155                        defaultwidth=1000, 
156                        sequences = {  }, },
157          },
158          dynamics = {}, features = {}, processes = {}, 
159       }
160       k.resources = { unicodes = ttu, }
161       k.descriptions = {}
162       cache_chars[cid_name]  = { [655360] = k.characters }
163
164       -- tounicode エントリ
165       local cidp = {nil, nil}; local cidmo = cidm
166       tt, ttu, cidm = {}, {}, {}
167       open_cmap_file(cid_name .. "-UCS2",
168                      function(a) 
169                         a[2] = a[2] +1 ; return a
170                      end, 
171                      function(a) 
172                         cidp[1] = string.upper(string.sub(a,1,string.len(a)-4))
173                         cidp[2] = tonumber(string.sub(a,-4),16)
174                         return cidp
175                      end,
176                      function(a) return a[1] ..string.format('%04X',a[2])  end)
177       -- tt は cid -> tounicode になっているので cidm -> tounicode に変換
178       for i,v in ipairs(cidmo) do
179          k.characters[v].width = kx[3](i)
180          if v>=0xF0000 then
181             k.characters[v].tounicode = tt[i]
182          end
183       end
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.definers.analyze(name,size)
237    specification = fonts.definers.resolve(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.shared = nil
250    cachedata.shared = nil
251    if s.shared then
252       cachedata.shared = {}
253       local shared = cachedata.shared
254       for k, v in pairs(s.shared) do
255          shared[k] = v
256       end
257    end
258
259    -- characters & scaling
260    if size < 0 then size = -size * 655.36 end
261    local scale = size / 655360
262    local def_height =  0.88 * size -- character's default height (optimized for jfm-ujis.lua)
263    local def_depth =  0.12 * size  -- and depth.
264    if not cache_chars[cid_name][size] then
265       cache_chars[cid_name][size]  = {}
266       for k, v in pairs(cache_chars[cid_name][655360]) do
267          cache_chars[cid_name][size][k] = { 
268             index = v.index, width = v.width * scale, 
269             height = def_height, depth = def_depth, tounicode = v.tounicode,
270          }
271       end
272    end
273    fontdata.characters = cache_chars[cid_name][size]
274    cachedata.characters = cache_chars[cid_name][size]
275
276    local parameters = {}
277    for k, v in pairs(s.parameters) do
278       parameters[k] = v * scale
279    end
280    fontdata.parameters = parameters;                cachedata.parameters = parameters
281    fontdata.ascender = fontdata.ascender * scale;   cachedata.ascender = fontdata.ascender
282    fontdata.descender = fontdata.descender * scale; cachedata.descender = fontdata.descender
283    fontdata.factor = fontdata.factor * scale;       cachedata.factor = fontdata.factor
284    fontdata.hfactor = fontdata.hfactor * scale;     cachedata.hfactor = fontdata.hfactor
285    fontdata.vfactor = fontdata.vfactor * scale;     cachedata.vfactor = fontdata.vfactor
286    fontdata.size = size;                            cachedata.size = size
287    fontdata.resources = s.resources
288    cachedata.resources = s.resources
289    
290    -- no embedding
291    local var = ''
292   --  if features.slant then 
293   --     fontdata.slant = features.slant*1000;         cachedata.slant = fontdata.slant
294   --     var = var .. 's' .. tostring(features.slant)
295   --  end
296   --  if features.extend then 
297   --     fontdata.extend = features.extend*1000;       cachedata.extend = fontdata.extend
298   --      var = var .. 'x' .. tostring(features.extend)
299   --  end
300    fontdata.name = specification.name .. size .. var; cachedata.name = fontdata.name
301    fontdata.fullname = specification.name .. var; cachedata.fullname = fontdata.fullname
302    fontdata.psname = specification.name; cachedata.psname = fontdata.psname
303    fonts.ids[id] = cachedata
304
305    return fontdata
306 end
307
308 function font_callback(name, size, id, fallback)
309    local p = utf.find(name, ":") or utf.len(name)+1
310    if utf.sub(name, 1, p-1) == 'psft' then
311       local s = "Adobe-Japan1-6"
312       local basename = utf.sub(name,p+1)
313       local p = utf.find(basename, ":")
314       if p then 
315          local xname = utf.sub(basename, p+1)
316          p = 1
317          while p do
318             local q = utf.find(xname, ";", p+1) or utf.len(xname)+1
319             if utf.sub(xname, p, p+3)=='cid=' and q>p+4 then
320                s = utf.sub(xname, p+4, q-1)
321             end
322             if utf.len(xname)+1==q then p = nil else p = q + 1 end
323          end
324       end
325       cid_reg, cid_order = string.match(s, "^(.-)%-(.-)%-(%d-)$")
326       if not cid_reg then 
327          cid_reg, cid_order = string.match(s, "^(.-)%-(.-)$")
328       end
329       cid_name = cid_reg .. '-' .. cid_order
330       if not cidfont_data[cid_name] then 
331          read_cid_font()
332          if not cidfont_data[cid_name] then 
333             ltjb.package_error('luatexja',
334                                "bad cid key `" .. s .. "'",
335                                "I couldn't find any non-embedded font information for the CID\n" ..
336                                   '`' .. s .. "'. For now, I'll use `Adobe-Japan1-6'.\n"..
337                                   'Please contact the LuaTeX-ja project team.')
338             cid_name = "Adobe-Japan1"
339          end
340       end
341       return mk_rml(basename, size, id)
342    else 
343       return fallback(name, size, id)
344    end
345 end
346
347 cid_reg, cid_order, cid_name, cid_supp = 'Adobe', 'Japan1', 'Adobe-Japan1'
348 read_cid_font()