OSDN Git Service

18ac8667dbe32859e6dd428cdf4d1a16ce2acdb5
[luatex-ja/luatexja.git] / src / ltj-rmlgbm.lua
1 --
2 -- ltj-rmlgbm.lua
3 --
4 luatexja.load_module 'base';      local ltjb = luatexja.base
5
6 local cidfont_data = {}
7 local cache_chars = {}
8 local cache_ver = 11
9 local identifiers = fonts.hashes.identifiers
10
11 local cid_reg, cid_order, cid_supp, cid_name
12 local cid_replace = {
13    ["Adobe-Japan1"] = {"UniJIS2004-UTF32", 23059, 7,
14                        function (i)
15                           if (231<=i and i<=632) or (8718<=i and i<=8719)
16                              or (12063<=i and i<=12087) then
17                              return 327680 -- 655360/2
18                           elseif 9758<=i and i<=9778 then
19                              return 218453 -- 655360/3
20                           elseif 9738<=i and i<=9757 then
21                              return 163840 -- 655360/4
22                           end
23                        end},
24                        -- 基本的には JIS X 0213:2004 に沿ったマッピング
25    ["Adobe-Korea1"] = {"UniKS-UTF32",  18351, 2,
26                        function (i)
27                           if 8094<=i and i<=8100 then
28                              return 327680 -- 655360/2
29                           end
30                        end},
31    ["Adobe-GB1"]    = {"UniGB-UTF32",  30283, 5,
32                        function (i)
33                           if (814<=i and i<=939) or (i==7716)
34                              or (22355<=i and i<=22357) then
35                              return 327680 -- 655360/2
36                           end
37                        end},
38    ["Adobe-CNS1"]   = {"UniCNS-UTF32", 19178, 7,
39                        function (i)
40                           if (13648<=i and i<=13742) or (i==17603) then
41                              return 327680 -- 655360/2
42                           end
43                        end},
44    ["Adobe-KR"] = {"UniAKR-UTF32", 22896, 9,
45                        function (i)
46                           if i==3057 then
47                              return 655360*2
48                           elseif i==3058 then
49                              return 655360*3
50                           elseif i==12235 or i==12236 then
51                              return 163840 -- 655360/4
52                           end
53                        end},
54 }
55
56 -- reading CID maps
57 local make_cid_font
58 do
59    local line, fh -- line, file handler
60    local tt,cidm -- characters, cid->(Unicode)
61
62    local function load_cid_char(cid_dec, mke)
63       local cid, ucs, ucsa
64       line = fh:read("*l")
65       while line do
66          if string.find(line, "end...?char") then
67             line = fh:read("*l"); return
68          else -- WMA l is in the form "<%x+>%s%d+"
69             ucs, cid = string.match(line, "<(%x+)>%s+<?(%x+)>?")
70             cid = cid_dec(cid); ucs = tonumber(ucs, 16);
71             if not tt[ucs]  then
72                tt[ucs] = mke(cid); cidm[cid]=ucs
73             end
74          end
75          line = fh:read("*l")
76       end
77    end
78
79    local function load_cid_range(inc, cid_dec, mke)
80       local bucs, eucs, cid
81       line = fh:read("*l")
82       while line do
83         if string.find(line, "end...?range") then
84             line = fh:read("*l"); return
85          else -- WMA l is in the form "<%x+>%s+<%x+>"
86             bucs, eucs, cid = string.match(line, "<(%x+)>%s+<(%x+)>%s+<?(%x+)>?")
87             cid = cid_dec(cid);
88             bucs = tonumber(bucs, 16); eucs = tonumber(eucs, 16)
89             for ucs = bucs, eucs do
90                if not tt[ucs]  then
91                   tt[ucs] = mke(cid); cidm[cid]=ucs
92                end
93                cid = inc(cid)
94             end
95          end
96          line = fh:read("*l")
97       end
98    end
99
100    local function open_cmap_file(name, inc, cid_dec, mke)
101       local fn = kpse.find_file(name, 'cmap files')
102       if fn then
103          fh = io.open(fn, "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    end
117
118    local function increment(a) return a+1 end
119    local function entry(a)
120       return {index = a}
121    end
122    local feat_dummy_vert = { gsub={vert={dflt={dflt=true}}} }
123    local seq_dummy_vert={{
124      features={vert={dflt={dflt=true}}},
125      --flags={false,false,false,false},
126      --index=1, name="s_s_0", skiphash=false, steps={coverage={},index=1},
127      ["type"]="gsub_single", order='vert',
128    }}
129    make_cid_font = function ()
130       local kx = cid_replace[cid_name]
131       if not kx then return end
132       local k = {
133          cidinfo = { ordering=cid_order, registry=cid_reg, supplement=kx[3] },
134          encodingbytes = 2, extend=1000, format = 'opentype',
135          direction = 0, characters = {}, parameters = {
136             ascender = 655360*0.88,
137             descender = 655360*0.12,
138          },
139          embedding = "no", cache = "yes", factor = 0, hfactor = 0, vfactor = 0,
140          tounicode = 1,
141          properties = { language = "dflt", script = "dflt" },
142       }
143       cidfont_data[cid_name] = k
144
145       -- CID => Unicode 符号空間
146       local tth, cidmo = {}, {}
147       tt, cidm = tth, cidmo
148       for i = 0,kx[2] do cidm[i] = -1 end
149       open_cmap_file(kx[1] .. "-H", increment, tonumber, entry)
150       k.characters = tth
151
152       -- Unicode にマップされなかった文字の処理
153       -- これらは TrueType フォントを使って表示するときはおかしくなる
154       local ttu, pricode = {}, 0xF0000
155       for i,v in ipairs(cidmo) do
156          if v==-1 then
157             tth[pricode], cidmo[i], pricode
158                = { index = i }, pricode, pricode+1;
159          end
160          ttu[i] = cidmo[i]
161          ttu[cid_order .. '.' .. i] = cidmo[i]
162       end
163
164       -- shared
165       k.shared = {
166          otfdata = {
167             cidinfo= k.cidinfo, verbose = false,
168             shared = { featuredata = {}, },
169          },
170          dynamics = {}, processes = {},
171          rawdata = {}, features={},
172       }
173       k.resources = {
174          unicodes = ttu,
175          features = feat_dummy_vert,
176          sequences = seq_dummy_vert,
177       }
178       k.descriptions = {}
179       cache_chars[cid_name]  = { [655360] = k.characters }
180
181       -- 縦書用字形
182       tt, cidm = {}, {}
183       local ttv = {}; k.ltj_vert_table = ttv
184       for i = 0,kx[2] do cidm[i] = -1 end
185       open_cmap_file(kx[1] .. "-V", increment, tonumber, entry)
186       for i,v in pairs(tt) do
187          ttv[i] =  cidmo[v.index] -- "unicode" of vertical variant
188       end
189
190       -- tounicode エントリ
191       local cidp = {nil, nil}; tt, ttu, cidm = {}, {}, {}
192       open_cmap_file(cid_name .. "-UCS2",
193                      function(a)
194                         a[2] = a[2] +1 ; return a
195                      end,
196                      function(a)
197                         cidp[1] = string.upper(string.sub(a,1,string.len(a)-4))
198                         cidp[2] = tonumber(string.sub(a,-4),16)
199                         return cidp
200                      end,
201                      function(a) return a[1] ..string.format('%04X',a[2])  end)
202       -- tt は cid -> tounicode になっているので cidm -> tounicode に変換
203       local kxf = kx[4]
204       for i,v in ipairs(cidmo) do
205          k.characters[v].width = kxf(i)
206          if v>=0xF0000 then
207             k.characters[v].tounicode = tt[i]
208          end
209       end
210
211       -- Save
212       if k and k.characters and k.characters[46] then
213         k.characters[46].width = math.floor(655360/14);
214       end
215       ltjb.save_cache("ltj-cid-auto-" .. string.lower(cid_name),
216                       {version = cache_ver, k})
217       k.shared.rawdata.resources=k.resources
218       k.shared.rawdata.descriptions=k.descriptions
219    end
220 end
221
222 --
223 local cidf_vert_processor
224 do
225    local traverse_glyph, is_node = node.direct.traverse_glyph, node.is_node
226    local to_direct = node.direct.todirect
227    local id_glyph = node.id 'glyph'
228    local getfont = node.direct.getfont
229    local getchar = node.direct.getchar
230    local setchar = node.direct.setchar
231    local font_getfont = font.getfont
232    cidf_vert_processor = {
233       function (head, fnum)
234          local fontdata = font_getfont(fnum)
235          if head and luatexja.jfont.font_metric_table[fnum] and luatexja.jfont.font_metric_table[fnum].vert_activated then
236             local vt = fontdata.ltj_vert_table
237             local nh = is_node(head) and to_direct(head) or head
238             for n in traverse_glyph(head) do
239                local c = getchar(n)
240                if getfont(n)==fnum then setchar(n, vt[c] or c) end
241             end
242             return head, false
243          end
244       end
245    }
246 end
247
248 local dummy_vht, dummy_vorg = {}, {}
249 setmetatable(dummy_vht, {__index = function () return 1 end } )
250 setmetatable(dummy_vorg, {__index = function () return 0.88 end } )
251 local function cid_cache_outdated(t) return t.version~=cache_ver end
252 local function read_cid_font()
253    local dat = ltjb.load_cache("ltj-cid-auto-" .. string.lower(cid_name),
254                                cid_cache_outdated)
255    if dat then
256       dat[1].shared.rawdata.resources=dat[1].resources
257       dat[1].shared.rawdata.descriptions=dat[1].descriptions
258       cidfont_data[cid_name] = dat[1]
259       cache_chars[cid_name]  = { [655360] = cidfont_data[cid_name].characters }
260    else
261       -- Now we must create the virtual metrics from CMap.
262       make_cid_font()
263    end
264    if cidfont_data[cid_name] then
265       cidfont_data[cid_name].shared.processes = cidf_vert_processor
266       cidfont_data[cid_name].resources.ltj_extra
267         = { ind_to_uni = cidfont_data[cid_name].resources.unicodes,
268             vheight = dummy_vht, vorigin = dummy_vorg }
269       for i,v in pairs(cidfont_data[cid_name].characters) do
270          if not v.width then v.width = 655360 end
271          v.height, v.depth = 576716.8, 78643.2 -- optimized for jfm-ujis.lua
272       end
273       return cidfont_data[cid_name]
274    else
275       return nil
276    end
277 end
278
279 -- High-level
280 local function prepare_cid_font(reg, ord)
281    cid_reg, cid_order, cid_name, cid_supp = reg, ord, reg .. '-' .. ord
282    return cidfont_data[cid_name] or read_cid_font()
283 end
284
285
286 local definers = fonts.definers
287 local function mk_rml(name, size, id)
288    local specification = definers.analyze(name,size)
289    --specification = definers.resolve(specification) (not needed)
290    specification.detail = specification.detail or ''
291    do
292       local n = specification.name
293       if n:sub(1,1)=="{" then n=n:sub(2) end
294       if n:sub(-1)=="}" then  n=n:sub(1,-2) end
295       specification.name=n
296    end
297    local fontdata = {}
298    local cachedata = {}
299    local s = cidfont_data[cid_name]
300    for k, v in pairs(s) do
301       fontdata[k] = v
302       cachedata[k] = v
303    end
304    fontdata.characters = nil
305    cachedata.characters = nil
306    fontdata.shared = nil
307    cachedata.shared = nil
308    if s.shared then
309       cachedata.shared = {}
310       local shared = cachedata.shared
311       for k, v in pairs(s.shared) do
312          shared[k] = v
313       end
314    end
315
316    -- characters & scaling
317    if size < 0 then size = -size * 655.36 end
318    local scale = size / 655360
319
320    do
321       local def_height =  0.88 * size
322       -- character's default height (optimized for jfm-ujis.lua)
323       local def_depth =  0.12 * size  -- and depth.
324       if not cache_chars[cid_name][size] then
325          cache_chars[cid_name][size]  = {}
326          for k, v in pairs(cache_chars[cid_name][655360]) do
327             cache_chars[cid_name][size][k] = {
328                index = v.index, width = v.width * scale,
329                height = def_height, depth = def_depth, tounicode = v.tounicode,
330             }
331          end
332       end
333       fontdata.characters = cache_chars[cid_name][size]
334       cachedata.characters = cache_chars[cid_name][size]
335    end
336    luatexja.rmlgbm.vert_addfunc(id, fontdata)
337
338    -- other parameters
339    do
340       local parameters = {}
341       for k, v in pairs(s.parameters) do  parameters[k] = v * scale end
342       fontdata.parameters  = parameters; fontdata.size  = size; fontdata.resources  = s.resources
343       cachedata.parameters = parameters; cachedata.size = size; cachedata.resources = s.resources
344    end
345
346    -- no embedding
347    local var = ''
348    local s = string.match(specification.detail, 'slant=([+-]*%d*%.?%d)')
349    if s and e~=0  then
350       s = s * 1000
351       var, fontdata.slant  = var .. 's' .. tostring(s), s
352    end
353    local e = string.match(specification.detail, 'extend=([+-]*%d*%.?%d)')
354    if e and e~=1  then
355       e = e * 1000
356       var, fontdata.extend  = var .. 'x' .. tostring(e), e
357    end
358    fontdata.name = specification.name .. size .. var; cachedata.name = fontdata.name
359    fontdata.fullname = specification.name .. var; cachedata.fullname = fontdata.fullname
360    fontdata.psname = specification.name; cachedata.psname = fontdata.psname
361    identifiers[id] = cachedata
362
363    return fontdata
364 end
365
366 local function font_callback(name, size, id, fallback)
367    if name:sub(1,1)=="{" and name:sub(-1)=="}" then name = name:sub(2,-2) end
368    local p = name:find(":") or 0
369    if name:sub(1, p-1) == 'psft' then
370       local s = "Adobe-Japan1-7"
371       local basename = name:sub(p+1)
372       local p = basename:find(":")
373       local q = basename:find("/[BI][BI]?")
374       if q and p and q<=p then
375          basename = basename:gsub('/[BI][BI]?', '', 1)
376          p = basename:find(":")
377       end
378       if p then
379          local xname = basename:sub(p+1)
380          p = 1
381          while p do
382             local q = xname:find(";", p+1) or xname:len()+1
383             if xname:sub(p, p+3)=='cid=' and q>p+4 then
384                s = xname:sub(p+4, q-1)
385             end
386             if xname:len()+1==q then p = nil else p = q + 1 end
387          end
388       end
389       cid_reg, cid_order = string.match(s, "^(.-)%-(.-)%-(%d-)$")
390       if not cid_reg then
391          cid_reg, cid_order = string.match(s, "^(.-)%-(.-)$")
392       end
393       if not prepare_cid_font(cid_reg, cid_order) then
394          ltjb.package_error('luatexja',
395                             "bad cid key `" .. s .. "'",
396                             "I couldn't find any non-embedded font information for the CID\n" ..
397                             '`' .. s .. "'. For now, I'll use `Adobe-Japan1-6'.\n"..
398                             'Please contact the LuaTeX-ja project team.')
399          cid_name = "Adobe-Japan1"
400       end
401       return mk_rml(basename, size, id)
402    else
403       local fontdata=fallback(name, size, id)
404       if type (fontdata) == "table" and fontdata.encodingbytes == 2 then
405         luatexbase.call_callback ("luaotfload.patch_font", fontdata, name, id)
406       else
407         luatexbase.call_callback ("luaotfload.patch_font_unsafe", fontdata, name, id)
408       end
409       return fontdata
410    end
411 end
412
413 luatexja.rmlgbm = {
414    prepare_cid_font = prepare_cid_font,
415    cidfont_data = cidfont_data,
416    font_callback = font_callback,
417    vert_addfunc = function () end, -- dummy, set in ltj-direction.lua
418 }
419
420 prepare_cid_font('Adobe', 'Japan1')