OSDN Git Service

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