OSDN Git Service

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