OSDN Git Service

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