OSDN Git Service

ltj-otf.lua: IVS now works with OTF (similar way as ivslist.tex)
[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/05/14',
7   description = 'Definitions of non-embedded Japanese (or other CJK) fonts',
8 })
9 module('luatexja.rmlgbm', package.seeall)
10 local err, warn, info, log = luatexbase.errwarinf(_NAME)
11
12 luatexja.load_module('base');      local ltjb = luatexja.base
13
14 cidfont_data = {}
15 local cidfont_data = cidfont_data
16 local cache_chars = {}
17 local path           = {
18     localdir  = kpse.expand_var("$TEXMFVAR"),
19     systemdir = kpse.expand_var("$TEXMFSYSVAR"),
20 }
21 local cache_dir = '/luatexja'
22
23 local cid_reg, cid_order, cid_supp, cid_name
24 local cid_replace = {
25    ["Adobe-Japan1"] = {"UniJIS2004-UTF32", 23057, 6,
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                        -- 基本的には JIS X 0213:2004 に沿ったマッピング
37    ["Adobe-Korea1"] = {"UniKS-UTF32",  18351, 2, 
38                        function (i)
39                           if 8094<=i and i<=8100 then 
40                              return 327680 -- 655360/2
41                           end
42                        end},
43    ["Adobe-GB1"]    = {"UniGB-UTF32",  30283, 5, 
44                        function (i)
45                           if (814<=i and i<=939) or (i==7716) 
46                              or (22355<=i and i<=22357) then
47                              return 327680 -- 655360/2
48                           end
49                        end},
50    ["Adobe-CNS1"]   = {"UniCNS-UTF32", 19155, 6,
51                        function (i)
52                           if (13648<=i and i<=13742) or (i==17603) then
53                              return 327680 -- 655360/2
54                           end
55                        end},
56 }
57
58 -- reading CID maps
59 do
60    local line, fh -- line, file handler
61    local tt,cidm -- characters, cid->(Unicode)
62
63    local function load_cid_char(cid_dec, mke)
64       local cid, ucs, ucsa
65       line = fh:read("*l")
66       while line do
67          if string.find(line, "end...?char") then 
68             line = fh:read("*l"); return
69          else -- WMA l is in the form "<%x+>%s%d+"
70             ucs, cid = string.match(line, "<(%x+)>%s+<?(%x+)>?")
71             cid = cid_dec(cid); ucs = tonumber(ucs, 16); 
72             if not tt[ucs]  then 
73                tt[ucs] = mke(cid); cidm[cid]=ucs
74             end
75          end
76          line = fh:read("*l")
77       end
78    end
79
80    local function load_cid_range(inc, cid_dec, mke)
81       local bucs, eucs, cid
82       line = fh:read("*l")
83       while line do
84         if string.find(line, "end...?range") then 
85             line = fh:read("*l"); return
86          else -- WMA l is in the form "<%x+>%s+<%x+>"
87             bucs, eucs, cid = string.match(line, "<(%x+)>%s+<(%x+)>%s+<?(%x+)>?")
88             cid = cid_dec(cid); 
89             bucs = tonumber(bucs, 16); eucs = tonumber(eucs, 16)
90             for ucs = bucs, eucs do
91                if not tt[ucs]  then 
92                   tt[ucs] = mke(cid); cidm[cid]=ucs
93                end
94                cid = inc(cid)
95             end
96          end
97          line = fh:read("*l")
98       end
99    end
100
101    local function open_cmap_file(name, inc, cid_dec, mke)
102       fh = io.open(kpse.find_file(name, 'cmap files'), "r")
103       line = fh:read("*l")
104       while line do
105          if string.find(line, "%x+%s+begin...?char") then
106             load_cid_char(cid_dec, mke)
107          elseif string.find(line, "%x+%s+begin...?range") then
108             load_cid_range(inc, cid_dec, mke)
109          else
110             line = fh:read("*l")
111          end
112       end
113       fh:close();  
114    end
115    
116    local function increment(a) return a+1 end
117    local function entry(a)     
118       return {index = a} 
119    end
120    function make_cid_font()
121       local kx = cid_replace[cid_name]
122       if not kx then return end
123       local k = {
124          cidinfo = { ordering=cid_order, registry=cid_reg, supplement=kx[3] },
125          encodingbytes = 2, extend=1000, format = 'opentype',
126          direction = 0, characters = {}, parameters = {}, embedding = "no", cache = "yes", 
127          ascender = 0, descender = 0, factor = 0, hfactor = 0, vfactor = 0,
128          tounicode = 1,
129       }
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       local kxf = kx[4]
179       for i,v in ipairs(cidmo) do
180          k.characters[v].width = kxf(i)
181          if v>=0xF0000 then
182             k.characters[v].tounicode = tt[i]
183          end
184       end
185
186       -- Save
187       local savepath  = path.localdir .. cache_dir
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          ltjb.package_info_no_line('luatexja', "saved :'" .. savepath .. "'", '')
198       else 
199          ltjb.package_warning_no_line('luatexja', "failed to save to '" .. savepath .. "'", '')
200       end
201    end
202 end
203 local make_cid_font = make_cid_font
204
205 -- 
206 local function cid_cache_load(fullpath)
207    cidfont_data[cid_name] = require(fullpath)
208    cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
209 end
210
211 local function read_cid_font()
212    -- local v = "ltj-cid-" .. string.lower(cid_name) .. ".lua"
213    local v = "ltj-cid-auto-" .. string.lower(cid_name) .. ".lua"
214    local localpath  = file.join(path.localdir, cache_dir, v)
215    local systempath = file.join(path.systemdir, cache_dir , v)
216    local kpsefound  = kpse.find_file(v)
217    if kpsefound and file.isreadable(kpsefound) then
218       cid_cache_load(kpsefound)
219    elseif file.isreadable(localpath)  then
220       cid_cache_load(localpath)
221    elseif file.isreadable(systempath) then
222       cid_cache_load(systempath)
223    else
224       -- Now we must create the virtual metrics from CMap.
225       make_cid_font()
226    end
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
237 local definers = fonts.definers
238 local function mk_rml(name, size, id)
239    local specification = definers.analyze(name,size)
240    specification = definers.resolve(specification)
241    specification.detail = specification.detail or ''
242
243    local fontdata = {}
244    local cachedata = {}
245    local s = cidfont_data[cid_name]
246    for k, v in pairs(s) do
247       fontdata[k] = v
248       cachedata[k] = v
249    end
250    fontdata.characters = nil
251    cachedata.characters = nil
252    fontdata.shared = nil
253    cachedata.shared = nil
254    if s.shared then
255       cachedata.shared = {}
256       local shared = cachedata.shared
257       for k, v in pairs(s.shared) do
258          shared[k] = v
259       end
260    end
261
262    -- characters & scaling
263    if size < 0 then size = -size * 655.36 end
264    local scale = size / 655360
265
266    do
267       local def_height =  0.88 * size 
268       -- character's default height (optimized for jfm-ujis.lua)
269       local def_depth =  0.12 * size  -- and depth.
270       if not cache_chars[cid_name][size] then
271          cache_chars[cid_name][size]  = {}
272          for k, v in pairs(cache_chars[cid_name][655360]) do
273             cache_chars[cid_name][size][k] = { 
274                index = v.index, width = v.width * scale, 
275                height = def_height, depth = def_depth, tounicode = v.tounicode,
276             }
277          end
278       end
279       fontdata.characters = cache_chars[cid_name][size]
280       cachedata.characters = cache_chars[cid_name][size]
281    end
282
283    -- other parameters
284    do
285       local parameters = {}
286       for k, v in pairs(s.parameters) do
287          parameters[k] = v * scale
288       end
289       fontdata.parameters  = parameters
290       fontdata.ascender    = fontdata.ascender * scale
291       fontdata.descender   = fontdata.descender * scale
292       fontdata.factor      = fontdata.factor * scale
293       fontdata.hfactor     = fontdata.hfactor * scale
294       fontdata.vfactor     = fontdata.vfactor * scale
295       fontdata.size        = size
296       fontdata.resources   = s.resources
297       cachedata.parameters = parameters
298       cachedata.ascender   = fontdata.ascender
299       cachedata.descender  = fontdata.descender
300       cachedata.factor     = fontdata.factor
301       cachedata.hfactor    = fontdata.hfactor
302       cachedata.vfactor    = fontdata.vfactor
303       cachedata.size       = size
304       cachedata.resources  = s.resources
305    end
306
307    -- no embedding
308    local var = ''
309    local s = string.match(specification.detail, 'slant=([+-]*%d*%.?%d)')
310    if s and e~=0  then 
311       s = s * 1000
312       var, fontdata.slant  = var .. 's' .. tostring(s), s
313    end
314    local e = string.match(specification.detail, 'extend=([+-]*%d*%.?%d)')
315    if e and e~=1  then 
316       e = e * 1000
317       var, fontdata.extend  = var .. 'x' .. tostring(e), e
318    end
319    fontdata.name = specification.name .. size .. var; cachedata.name = fontdata.name
320    fontdata.fullname = specification.name .. var; cachedata.fullname = fontdata.fullname
321    fontdata.psname = specification.name; cachedata.psname = fontdata.psname
322    fonts.hashes.identifiers[id] = cachedata
323
324    return fontdata
325 end
326
327 function font_callback(name, size, id, fallback)
328    local p = utf.find(name, ":") or utf.len(name)+1
329    if utf.sub(name, 1, p-1) == 'psft' then
330       local s = "Adobe-Japan1-6"
331       local basename = utf.sub(name,p+1)
332       local p = utf.find(basename, ":")
333       local q = utf.find(basename, "/[BI][BI]?")
334       if q and p and q<=p then
335          basename = utf.gsub(basename, '/[BI][BI]?', '', 1)
336          p = utf.find(basename, ":")
337       end
338       if p then 
339          local xname = utf.sub(basename, p+1)
340          p = 1
341          while p do
342             local q = utf.find(xname, ";", p+1) or utf.len(xname)+1
343             if utf.sub(xname, p, p+3)=='cid=' and q>p+4 then
344                s = utf.sub(xname, p+4, q-1)
345             end
346             if utf.len(xname)+1==q then p = nil else p = q + 1 end
347          end
348       end
349       cid_reg, cid_order = string.match(s, "^(.-)%-(.-)%-(%d-)$")
350       if not cid_reg then 
351          cid_reg, cid_order = string.match(s, "^(.-)%-(.-)$")
352       end
353       cid_name = cid_reg .. '-' .. cid_order
354       if not cidfont_data[cid_name] then 
355          read_cid_font()
356          if not cidfont_data[cid_name] then 
357             ltjb.package_error('luatexja',
358                                "bad cid key `" .. s .. "'",
359                                "I couldn't find any non-embedded font information for the CID\n" ..
360                                   '`' .. s .. "'. For now, I'll use `Adobe-Japan1-6'.\n"..
361                                   'Please contact the LuaTeX-ja project team.')
362             cid_name = "Adobe-Japan1"
363          end
364       end
365       return mk_rml(basename, size, id)
366    else 
367       return fallback(name, size, id)
368    end
369 end
370
371 cid_reg, cid_order, cid_name, cid_supp = 'Adobe', 'Japan1', 'Adobe-Japan1'
372 read_cid_font()