OSDN Git Service

Changed version of all files to 2013/05/14.
[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, 6,
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, 2, 
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, 5, 
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, 6,
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 kx = cid_replace[cid_name]
123       if not kx then return end
124       local k = {
125          cidinfo = { ordering=cid_order, registry=cid_reg, supplement=kx[3] },
126          encodingbytes = 2, extend=1000, format = 'opentype',
127          direction = 0, characters = {}, parameters = {}, embedding = "no", cache = "yes", 
128          ascender = 0, descender = 0, factor = 0, hfactor = 0, vfactor = 0,
129          tounicode = 1,
130       }
131       cidfont_data[cid_name] = k
132
133       -- CID => Unicode 符号空間
134       -- TODO: vertical fonts?
135       tt, cidm = {}, {}
136       for i = 0,kx[2] do cidm[i] = -1 end
137       open_cmap_file(kx[1] .. "-H", increment, tonumber, entry)
138       k.characters = tt
139
140       -- Unicode にマップされなかった文字の処理
141       -- これらは TrueType フォントを使って表示するときはおかしくなる
142       local ttu, pricode = {}, 0xF0000
143       for i,v in ipairs(cidm) do
144          if v==-1 then 
145             tt[pricode], cidm[i], pricode 
146                = { index = i }, pricode, pricode+1;
147          end
148          ttu[cid_order .. '.' .. i] = cidm[i]
149       end
150       -- shared
151       k.shared = {
152          otfdata = { 
153             cidinfo= k.cidinfo, verbose = false, 
154             shared = { featuredata = {}, }, 
155             luatex = { features = {}, 
156                        defaultwidth=1000, 
157                        sequences = {  }, },
158          },
159          dynamics = {}, features = {}, processes = {}, 
160       }
161       k.resources = { unicodes = ttu, }
162       k.descriptions = {}
163       cache_chars[cid_name]  = { [655360] = k.characters }
164
165       -- tounicode エントリ
166       local cidp = {nil, nil}; local cidmo = cidm
167       tt, ttu, cidm = {}, {}, {}
168       open_cmap_file(cid_name .. "-UCS2",
169                      function(a) 
170                         a[2] = a[2] +1 ; return a
171                      end, 
172                      function(a) 
173                         cidp[1] = string.upper(string.sub(a,1,string.len(a)-4))
174                         cidp[2] = tonumber(string.sub(a,-4),16)
175                         return cidp
176                      end,
177                      function(a) return a[1] ..string.format('%04X',a[2])  end)
178       -- tt は cid -> tounicode になっているので cidm -> tounicode に変換
179       local kxf = kx[4]
180       for i,v in ipairs(cidmo) do
181          k.characters[v].width = kxf(i)
182          if v>=0xF0000 then
183             k.characters[v].tounicode = tt[i]
184          end
185       end
186
187       -- Save
188       local savepath  = path.localdir .. '/luatexja/'
189       if not lfs.isdir(savepath) then
190          dir.mkdirs(savepath)
191       end
192       savepath = file.join(savepath, "ltj-cid-auto-" 
193                            .. string.lower(cid_name)  .. ".lua")
194       if file.iswritable(savepath) then
195          k.characters[46].width = math.floor(655360/14);
196          -- Standard fonts are ``seriffed''. 
197          table.tofile(savepath, k,'return', false, true, false )
198          ltjb.package_info_no_line('luatexja', "saved :'" .. savepath .. "'", '')
199       else 
200          ltjb.package_warning_no_line('luatexja', "failed to save to '" .. savepath .. "'", '')
201       end
202    end
203 end
204 local make_cid_font = make_cid_font
205
206 -- 
207 local function cid_cache_load(fullpath)
208    cidfont_data[cid_name] = require(fullpath)
209    cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
210 end
211
212 local function read_cid_font()
213    -- local v = "ltj-cid-" .. string.lower(cid_name) .. ".lua"
214    local v = "ltj-cid-auto-" .. string.lower(cid_name) .. ".lua"
215    local localpath  = file.join(path.localdir .. '/luatexja', v)
216    local systempath = file.join(path.systemdir .. '/luatexja' , v)
217    local kpsefound  = kpse.find_file(v)
218    if kpsefound and file.isreadable(kpsefound) then
219       cid_cache_load(kpsefound)
220    elseif file.isreadable(localpath)  then
221       cid_cache_load(localpath)
222    elseif file.isreadable(systempath) then
223       cid_cache_load(systempath)
224    else
225       -- Now we must create the virtual metrics from CMap.
226       make_cid_font()
227    end
228    if cidfont_data[cid_name] then
229       for i,v in pairs(cidfont_data[cid_name].characters) do
230          if not v.width then v.width = 655360 end
231          v.height, v.depth = 576716.8, 78643.2 -- optimized for jfm-ujis.lua
232       end
233    end
234 end
235
236 -- High-level
237
238 local definers = fonts.definers
239 local function mk_rml(name, size, id)
240    local specification = definers.analyze(name,size)
241    specification = definers.resolve(specification)
242    specification.detail = specification.detail or ''
243
244    local fontdata = {}
245    local cachedata = {}
246    local s = cidfont_data[cid_name]
247    for k, v in pairs(s) do
248       fontdata[k] = v
249       cachedata[k] = v
250    end
251    fontdata.characters = nil
252    cachedata.characters = nil
253    fontdata.shared = nil
254    cachedata.shared = nil
255    if s.shared then
256       cachedata.shared = {}
257       local shared = cachedata.shared
258       for k, v in pairs(s.shared) do
259          shared[k] = v
260       end
261    end
262
263    -- characters & scaling
264    if size < 0 then size = -size * 655.36 end
265    local scale = size / 655360
266
267    do
268       local def_height =  0.88 * size 
269       -- character's default height (optimized for jfm-ujis.lua)
270       local def_depth =  0.12 * size  -- and depth.
271       if not cache_chars[cid_name][size] then
272          cache_chars[cid_name][size]  = {}
273          for k, v in pairs(cache_chars[cid_name][655360]) do
274             cache_chars[cid_name][size][k] = { 
275                index = v.index, width = v.width * scale, 
276                height = def_height, depth = def_depth, tounicode = v.tounicode,
277             }
278          end
279       end
280       fontdata.characters = cache_chars[cid_name][size]
281       cachedata.characters = cache_chars[cid_name][size]
282    end
283
284    -- other parameters
285    do
286       local parameters = {}
287       for k, v in pairs(s.parameters) do
288          parameters[k] = v * scale
289       end
290       fontdata.parameters  = parameters
291       fontdata.ascender    = fontdata.ascender * scale
292       fontdata.descender   = fontdata.descender * scale
293       fontdata.factor      = fontdata.factor * scale
294       fontdata.hfactor     = fontdata.hfactor * scale
295       fontdata.vfactor     = fontdata.vfactor * scale
296       fontdata.size        = size
297       fontdata.resources   = s.resources
298       cachedata.parameters = parameters
299       cachedata.ascender   = fontdata.ascender
300       cachedata.descender  = fontdata.descender
301       cachedata.factor     = fontdata.factor
302       cachedata.hfactor    = fontdata.hfactor
303       cachedata.vfactor    = fontdata.vfactor
304       cachedata.size       = size
305       cachedata.resources  = s.resources
306    end
307
308    -- no embedding
309    local var = ''
310    local s = string.match(specification.detail, 'slant=([+-]*%d*%.?%d)')
311    if s and e~=0  then 
312       s = s * 1000
313       var, fontdata.slant  = var .. 's' .. tostring(s), s
314    end
315    local e = string.match(specification.detail, 'extend=([+-]*%d*%.?%d)')
316    if e and e~=1  then 
317       e = e * 1000
318       var, fontdata.extend  = var .. 'x' .. tostring(e), e
319    end
320    fontdata.name = specification.name .. size .. var; cachedata.name = fontdata.name
321    fontdata.fullname = specification.name .. var; cachedata.fullname = fontdata.fullname
322    fontdata.psname = specification.name; cachedata.psname = fontdata.psname
323    fonts.ids[id] = cachedata
324
325    return fontdata
326 end
327
328 function font_callback(name, size, id, fallback)
329    local p = utf.find(name, ":") or utf.len(name)+1
330    if utf.sub(name, 1, p-1) == 'psft' then
331       local s = "Adobe-Japan1-6"
332       local basename = utf.sub(name,p+1)
333       local p = utf.find(basename, ":")
334       local q = utf.find(basename, "/[BI][BI]?")
335       if q and p and q<=p then
336          basename = utf.gsub(basename, '/[BI][BI]?', '', 1)
337          p = utf.find(basename, ":")
338       end
339       if p then 
340          local xname = utf.sub(basename, p+1)
341          p = 1
342          while p do
343             local q = utf.find(xname, ";", p+1) or utf.len(xname)+1
344             if utf.sub(xname, p, p+3)=='cid=' and q>p+4 then
345                s = utf.sub(xname, p+4, q-1)
346             end
347             if utf.len(xname)+1==q then p = nil else p = q + 1 end
348          end
349       end
350       cid_reg, cid_order = string.match(s, "^(.-)%-(.-)%-(%d-)$")
351       if not cid_reg then 
352          cid_reg, cid_order = string.match(s, "^(.-)%-(.-)$")
353       end
354       cid_name = cid_reg .. '-' .. cid_order
355       if not cidfont_data[cid_name] then 
356          read_cid_font()
357          if not cidfont_data[cid_name] then 
358             ltjb.package_error('luatexja',
359                                "bad cid key `" .. s .. "'",
360                                "I couldn't find any non-embedded font information for the CID\n" ..
361                                   '`' .. s .. "'. For now, I'll use `Adobe-Japan1-6'.\n"..
362                                   'Please contact the LuaTeX-ja project team.')
363             cid_name = "Adobe-Japan1"
364          end
365       end
366       return mk_rml(basename, size, id)
367    else 
368       return fallback(name, size, id)
369    end
370 end
371
372 cid_reg, cid_order, cid_name, cid_supp = 'Adobe', 'Japan1', 'Adobe-Japan1'
373 read_cid_font()