OSDN Git Service

Forgot to include ltj-direction.lua^^;
[luatex-ja/luatexja.git] / src / ltj-direction.lua
1 --
2 -- src/ltj-direction.lua
3 --
4
5 luatexja.load_module('base');      local ltjb = luatexja.base
6 luatexja.load_module('stack');     local ltjs = luatexja.stack
7 luatexja.load_module('rmlgbm');    local ltjr = luatexja.rmlgbm
8 luatexja.direction = {}
9
10 local attr_dir = luatexbase.attributes['ltj@dir']
11 local attr_icflag = luatexbase.attributes['ltj@icflag']
12
13 local cat_lp = luatexbase.catcodetables['latex-package']
14 local Dnode = node.direct or node
15 local nullfunc = function (n) return n end
16 local to_node = (Dnode ~= node) and Dnode.tonode or nullfunc
17 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
18 local has_attr = Dnode.has_attribute
19 local set_attr = Dnode.set_attribute
20 local insert_before = Dnode.insert_before
21 local insert_after = Dnode.insert_after
22 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
23 local getsubtype = (Dnode ~= node) and Dnode.getsubtype or function(n) return n.subtype end
24 local getlist = (Dnode ~= node) and Dnode.getlist or function(n) return n.head end
25 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
26 local getfield = (Dnode ~= node) and Dnode.getfield or function(n, i) return n[i] end
27 local node_new = Dnode.new
28 local node_tail = Dnode.tail
29 local node_free = Dnode.free
30 local node_remove = Dnode.remove
31 local node_next = (Dnode ~= node) and Dnode.getnext or node.next
32 local traverse = Dnode.traverse
33 local traverse_id = Dnode.traverse_id
34 local start_time_measure, stop_time_measure 
35    = ltjb.start_time_measure, ltjb.stop_time_measure
36 local abs = math.abs
37
38 local id_kern = node.id('kern')
39 local id_hlist = node.id('hlist')
40 local id_vlist = node.id('vlist')
41 local id_whatsit = node.id('whatsit')
42 local sid_save = node.subtype('pdf_save')
43 local sid_restore = node.subtype('pdf_restore')
44 local sid_matrix = node.subtype('pdf_setmatrix')
45 local sid_user = node.subtype('user_defined')
46
47 local tex_nest = tex.nest
48 local tex_getcount = tex.getcount
49 local tex_set_attr = tex.setattribute
50 local PROCESSED    = luatexja.icflag_table.PROCESSED
51 local PROCESSED_BEGIN_FLAG = luatexja.icflag_table.PROCESSED_BEGIN_FLAG
52 local PACKED       = luatexja.icflag_table.PACKED
53 local STCK = luatexja.userid_table.STCK
54 local DIR  = luatexja.userid_table.DIR
55 local dir_tate = luatexja.dir_table.dir_tate
56 local dir_yoko = luatexja.dir_table.dir_yoko
57 local dir_dtou = luatexja.dir_table.dir_dtou
58 local dir_utod = luatexja.dir_table.dir_utod
59 local dir_math_mod    = luatexja.dir_table.dir_math_mod
60 local dir_node_auto   = luatexja.dir_table.dir_node_auto
61 local dir_node_manual = luatexja.dir_table.dir_node_manual
62
63 local page_direction
64 --
65 local function adjust_badness(hd)
66    if not node_next(hd) and getid(hd)==id_whatsit and getsubtype(hd)==sid_user
67    and getfield(hd, 'user_id')==DIR then
68       -- avoid double whatsit
69       luatexja.global_temp=tex.globaldefs; tex.globaldefs=0
70       luatexja.hbadness_temp=tex.hbadness; tex.hbadness=10000
71       luatexja.vbadness_temp=tex.vbadness; tex.vbadness=10000
72    else
73       luatexja.global_temp = nil
74       luatexja.hbadness_temp=nil
75       luatexja.vbadness_temp=nil
76    end
77 end
78
79 local get_dir_count, get_adjust_dir_count
80 do
81    local function get_dir_count_inner(h)
82       if h then
83          if h.id==id_whatsit and h.subtype==sid_user and h.user_id==DIR then
84                local ic = node.has_attribute(h, attr_icflag)
85                return (ic<PROCESSED_BEGIN_FLAG) 
86                   and (node.has_attribute(h,attr_dir)%dir_node_auto) or 0
87          else
88             return 0
89          end
90       else
91          return 0
92       end
93    end
94    function get_dir_count()
95       for i=tex_nest.ptr, 1, -1 do
96          local h = tex_nest[i].head.next
97          if h then
98             local t = get_dir_count_inner(h)
99             if t~=0 then return t end
100          end
101       end
102       return page_direction
103    end
104    function get_adjust_dir_count()
105       for i=tex_nest.ptr, 1, -1 do
106          local v = tex_nest[i]
107          local h, m = v.head.next, v.mode
108          if abs(m)== ltjs.vmode and h then
109             local t = get_dir_count_inner(h)
110             if t~=0 then return t end
111          end
112       end
113       return page_direction
114    end
115    luatexja.direction.get_dir_count = get_dir_count
116    luatexja.direction.get_adjust_dir_count = get_adjust_dir_count
117 end
118
119
120 -- \tate, \yoko,\dtou, \utod
121 do
122    local node_next = node.next
123    local node_set_attr = node.set_attribute
124    local function set_list_direction(v, name)
125       local lv, w = tex_nest.ptr, tex.lists.page_head
126       if not v then 
127          v,name  = get_dir_count(), nil
128          if lv>=1 and abs(tex_nest[lv-1].mode) == ltjs.mmode and v == dir_tate then
129             v = dir_utod
130          end
131       elseif v=='adj' then
132          v,name = get_adjust_dir_count(), nil
133       end
134       if tex.currentgrouptype==6 then
135          ltjb.package_error(
136                  'luatexja',
137                  "You can't use `\\" .. name .. "' in an align",
138                  "To change direction in an align, \n"
139                     .. "you shold use \\hbox or \\vbox.")
140       else
141          local w = (lv==0) and tex.lists.page_head or tex_nest[lv].head.next
142          if w then
143             if (not w.next) and 
144                w.id==id_whatsit and w.subtype==sid_user and w.user_id==DIR then
145                node_set_attr(w, attr_dir, v)
146                if lv==0 then page_direction = v end
147             elseif lv==0 and not page_direction then
148                page_direction = v -- for first call of \yoko (in luatexja-core.sty)
149             else
150               ltjb.package_error(
151                  'luatexja',
152                  "Use `\\" .. tostring(name) .. "' at top of list",
153                  'Direction change command by LuaTeX-ja is available\n'
154                     .. 'only when the current list is null.')
155             end
156          else
157             local w = node_new(id_whatsit, sid_user)
158             setfield(w, 'next', nil)
159             setfield(w, 'user_id', DIR)
160             setfield(w, 'type', 110)
161             set_attr(w, attr_dir, v)
162             Dnode.write(w)
163             if lv==0 then page_direction = v end
164          end
165          tex_set_attr('global', attr_icflag, 0)
166       end
167       tex_set_attr('global', attr_dir, 0)
168    end
169    luatexja.direction.set_list_direction = set_list_direction
170 end
171
172 -- ボックスに dir whatsit を追加
173 local function create_dir_whatsit(hd, gc, new_dir)
174    if getid(hd)==id_whatsit and 
175             getsubtype(hd)==sid_user and getfield(hd, 'user_id')==DIR then
176       set_attr(hd, attr_icflag, 
177                (has_attr(hd, attr_icflag) or 0)%PROCESSED_BEGIN_FLAG 
178                   + PROCESSED_BEGIN_FLAG)
179       tex_set_attr('global', attr_icflag, 0)
180       return hd
181    else
182       local w = node_new(id_whatsit, sid_user)
183       setfield(w, 'next', hd)
184       setfield(w, 'user_id', DIR)
185       setfield(w, 'type', 110)
186       set_attr(w, attr_dir, new_dir)
187       set_attr(w, attr_icflag, PROCESSED_BEGIN_FLAG)
188       set_attr(hd, attr_icflag, 
189                (has_attr(hd, attr_icflag) or 0)%PROCESSED_BEGIN_FLAG 
190                   + PROCESSED_BEGIN_FLAG)
191       tex_set_attr('global', attr_dir, 0)
192       tex_set_attr('global', attr_icflag, 0)
193       return w
194    end
195 end
196
197 -- hpack_filter, vpack_filter, post_line_break_filter
198 -- の結果を組方向を明示するため,先頭に dir_node を設置
199 do
200    local function create_dir_whatsit_hpack(h, gc)
201       local hd = to_direct(h)
202       if gc=='fin_row' or gc == 'preamble'  then
203          if hd  then
204             set_attr(hd, attr_icflag, PROCESSED_BEGIN_FLAG)
205             tex_set_attr('global', attr_icflag, 0)
206          end
207          return h
208       else
209          adjust_badness(hd)
210          return to_node(create_dir_whatsit(hd, gc, ltjs.list_dir))
211       end
212    end
213
214    luatexbase.add_to_callback('hpack_filter', 
215                               create_dir_whatsit_hpack, 'ltj.create_dir_whatsit', 10000)
216 end
217
218 do
219    local function create_dir_whatsit_parbox(h, gc)
220       stop_time_measure('tex_linebreak')
221       -- start 側は ltj-debug.lua に
222       local new_dir, hd = ltjs.list_dir, to_direct(h)
223       for line in traverse_id(id_hlist, hd) do
224          local nh = getlist(line)
225          setfield(line, 'head', create_dir_whatsit(nh, gc, new_dir) )
226          set_attr(line, attr_dir, new_dir)
227       end
228       tex_set_attr('global', attr_dir, 0)
229       return h 
230    end
231    luatexbase.add_to_callback('post_linebreak_filter', 
232                               create_dir_whatsit_parbox, 'ltj.create_dir_whatsit', 10000)
233 end
234
235 local create_dir_whatsit_vbox
236 do
237    local wh = {}
238    local id_glue, sid_parskip = node.id('glue'), 3
239    create_dir_whatsit_vbox = function (hd, gc)
240       ltjs.list_dir = get_dir_count()
241       -- remove dir whatsit
242       for x in traverse_id(id_whatsit, hd) do
243          if getsubtype(x)==sid_user and getfield(x, 'user_id')==DIR then
244             wh[#wh+1]=x
245          end
246       end
247       if hd==wh[1] then
248          ltjs.list_dir =has_attr(hd,attr_dir)
249          local x = node_next(hd)
250          if getid(x)==id_glue and getsubtype(x)==sid_parskip then
251             node_remove(hd,x); node_free(x)
252          end
253       end
254       for i=1,#wh do  
255          hd = node_remove(hd, wh[i]); node_free(wh[i]); wh[i] = nil 
256       end
257       if gc=='fin_row' then -- gc == 'preamble' case is treated in dir_adjust_vpack
258          if hd  then
259             set_attr(hd, attr_icflag, PROCESSED_BEGIN_FLAG)
260             tex_set_attr('global', attr_icflag, 0)
261          end
262          return hd
263       else
264          local n =node_next(hd)
265          if gc=='vtop' then
266             local w = create_dir_whatsit(hd, gc, ltjs.list_dir)
267             -- move  dir whatsit after hd
268             setfield(hd, 'next', w); setfield(w, 'next', n)
269             return hd
270          else
271             hd = create_dir_whatsit(hd, gc, ltjs.list_dir)
272             return hd
273          end
274       end
275    end
276 end
277
278 -- dir_node に包む方法を書いたテーブル
279 local dir_node_aux
280 do
281    local floor = math.floor
282    local get_h =function (w,h,d) return h end
283    local get_d =function (w,h,d) return d end
284    local get_h_d =function (w,h,d) return h+d end
285    local get_h_d_neg =function (w,h,d) return -h-d end
286    local get_d_neg =function (w,h,d) return -d end
287    local get_w_half =function (w,h,d) return floor(0.5*w) end
288    local get_w_half_rem =function (w,h,d) return w-floor(0.5*w) end
289    local get_w_neg =function (w,h,d) return -w end
290    local get_w =function (w,h,d) return w end
291    local zero = function() return 0 end
292    dir_node_aux = {
293       [dir_yoko] = { -- yoko を 
294          [dir_tate] = { -- tate 中で組む
295             width  = get_h_d,
296             height = get_w_half,
297             depth  = get_w_half_rem,
298             [id_hlist] = {
299                { 'whatsit', sid_save },
300                { 'rotate', '0 1 -1 0' },
301                { 'kern', function(w,h,d,nw,nh,nd) return -nd end },
302                { 'box' , get_h},
303                { 'kern', function(w,h,d,nw,nh,nd) return nd-w end },
304                { 'whatsit', sid_restore },
305             },
306             [id_vlist] = {
307                { 'whatsit', sid_save },
308                { 'rotate', '0 1 -1 0' },
309                { 'kern' , zero },
310                { 'box' , function(w,h,d,nw,nh,nd) return -nh-nd end },
311                { 'kern', get_h_d_neg},
312                { 'whatsit', sid_restore },
313             },
314          },
315          [dir_dtou] = { -- dtou 中で組む
316             width  = get_h_d,
317             height = get_w,
318             depth  = zero,
319             [id_hlist] = {
320                { 'whatsit', sid_save },
321                { 'rotate', '0 -1 1 0' },
322                { 'kern', function(w,h,d,nw,nh,nd) return -nh end },
323                { 'box', get_d_neg },
324                { 'kern', function(w,h,d,nw,nh,nd) return nh-w end },
325                { 'whatsit', sid_restore },
326             },
327             [id_vlist] = {
328                { 'whatsit', sid_save },
329                { 'rotate', '0 -1 1 0' },
330                { 'kern', get_h_d_neg },
331                { 'box', zero },
332                { 'whatsit', sid_restore },
333             },
334          },
335       },
336       [dir_tate] = { -- tate を
337          [dir_yoko] = { -- yoko 中で組む
338             width  = get_h_d,
339             height = get_w,
340             depth  = zero,
341             [id_hlist] = {
342                { 'whatsit', sid_save },
343                { 'rotate', '0 -1 1 0' },
344                { 'kern', function (w,h,d,nw,nh,nd) return -nh end },
345                { 'box' , get_d_neg },
346                { 'kern', function (w,h,d,nw,nh,nd) return nh-w end },
347                { 'whatsit', sid_restore },
348             },
349             [id_vlist] = {
350                { 'whatsit', sid_save },
351                { 'rotate', '0 -1 1 0' },
352                { 'kern', get_h_d_neg },
353                { 'box', zero },
354                { 'whatsit', sid_restore },
355             },
356          },
357          [dir_dtou] = { -- dtou 中で組む
358             width  = get_w,
359             height = get_d,
360             depth  = get_h,
361             [id_hlist] = {
362                { 'whatsit', sid_save },
363                { 'rotate', '-1 0 0 -1' },
364                { 'kern', get_w_neg },
365                { 'box',  function (w,h,d,nw,nh,nd) return h-nd end },
366                { 'whatsit', sid_restore },
367             },
368             [id_vlist] = {
369                { 'whatsit', sid_save },
370                { 'rotate', '-1 0 0 -1' },
371                { 'kern', get_h_d_neg },
372                { 'box', get_w_neg },
373                { 'whatsit', sid_restore },
374             },
375          },
376       },
377       [dir_dtou] = { -- dtou を
378          [dir_yoko] = { -- yoko 中で組む
379             width  = get_h_d,
380             height = get_w, 
381             depth  = zero,
382             [id_hlist] = {
383                { 'whatsit', sid_save },
384                { 'rotate', '0 1 -1 0' },
385                { 'kern', function (w,h,d,nw,nh,nd) return -nd end },
386                { 'box', get_h },
387                { 'kern', function (w,h,d,nw,nh,nd) return nd-w end },
388                { 'whatsit', sid_restore },
389             },
390             [id_vlist] = {
391                { 'kern', zero },
392                { 'whatsit', sid_save },
393                { 'rotate', '0 1 -1 0' },
394                { 'box', function (w,h,d,nw,nh,nd) return -nd-nh end },
395                { 'kern', get_h_d_neg },
396                { 'whatsit', sid_restore },
397             },
398          },
399          [dir_tate] = { -- tate 中で組む
400             width  = get_w,
401             height = get_d,
402             depth  = get_h,
403             [id_hlist] = {
404                { 'whatsit', sid_save },
405                { 'rotate', '-1 0 0 -1' },
406                { 'kern', get_w_neg },
407                { 'box', function (w,h,d,nw,nh,nd) return h-nd end },
408                { 'whatsit', sid_restore },
409             },
410             [id_vlist] = {
411                { 'whatsit', sid_save },
412                { 'rotate', ' -1 0 0 -1' },
413                { 'kern', function (w,h,d,nw,nh,nd) return -nh-nd end }, 
414                { 'box', get_w_neg },
415                { 'kern', function (w,h,d,nw,nh,nd) return nh+nd-h-d end }, 
416                { 'whatsit', sid_restore },
417             },
418          },
419       },
420    }
421 end
422
423 -- 1st ret val: b の組方向
424 -- 2nd ret val はその DIR whatsit
425 local function get_box_dir(b, default)
426    start_time_measure('get_box_dir')
427    local dir = has_attr(b, attr_dir) or 0
428    local bh = getfield(b,'head') 
429    -- b は insert node となりうるので getlist() は使えない
430    local c
431    for i=1,2 do
432       if bh and getid(bh)==id_whatsit
433       and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
434          c = bh
435          dir = (dir==0) and has_attr(bh, attr_dir) or dir
436       end
437       bh = node_next(bh)
438    end
439    stop_time_measure('get_box_dir')
440    return (dir==0 and default or dir), c
441 end
442
443 do
444    local getbox = tex.getbox
445    local function check_dir(reg_num)
446       start_time_measure('box_primitive_hook')
447       local list_dir = get_dir_count()%dir_math_mod
448       local b = getbox(tex_getcount('ltj@tempcnta'))
449       if b then
450          local box_dir = get_box_dir(to_direct(b), dir_yoko)
451          if box_dir%dir_math_mod ~= list_dir then
452            --  print('NEST', tex_nest.ptr, tex_getcount('ltj@tempcnta'))
453            --  luatexja.ext_show_node_list(
454            --     (tex_nest.ptr==0) and tex.lists.page_head or tex_nest[tex_nest.ptr].head,
455            --     'LIST' .. tostring(list_dir) .. '> ', print)
456            -- luatexja.ext_show_node_list(b, 'BOX' .. tostring(box_dir) .. '> ', print)
457             ltjb.package_error(
458                'luatexja',
459                "Incompatible direction list can't be unboxed",
460                'I refuse to unbox a box in differrent direction.')
461          end
462       end
463       if luatexja.global_temp and tex.globaldefs~=luatexja.global_temp then 
464          tex.globaldefs = luatexja.global_temp
465       end
466       stop_time_measure('box_primitive_hook')
467    end
468    luatexja.direction.check_dir = check_dir
469 end
470
471 -- dir_node に包まれている「本来の中身」を取り出し,
472 -- dir_node を全部消去
473 local function unwrap_dir_node(b, head, box_dir)
474    -- b: dir_node, head: the head of list, box_dir: 
475    -- return values are (new head), (next of b), (contents), (dir of contents)
476    local bh = getlist(b)
477    local bc = node_next(node_next(node_next(bh)))
478    local nh, nb
479    node_remove(bh, bc); 
480    Dnode.flush_list(bh)
481    if head then
482       nh = insert_before(head, b, bc)
483       nh, nb = node_remove(nh, b)
484       setfield(b, 'next', nil)
485       setfield(b, 'head', nil)
486       node_free(b)
487    end
488    local shift_old, b_dir, wh = nil, get_box_dir(bc, 0)
489    if wh then
490       Dnode.flush_list(getfield(wh, 'value'))
491       setfield(wh, 'value', nil)
492    end
493    setfield(bc, 'shift', 0)
494    return nh, nb, bc, b_dir
495 end
496
497 -- is_manual: 寸法変更に伴うものか?
498 local function create_dir_node(b, b_dir, new_dir, is_manual)
499    local info = dir_node_aux[b_dir%dir_math_mod][new_dir%dir_math_mod]
500    local w = getfield(b, 'width')
501    local h = getfield(b, 'height')
502    local d = getfield(b, 'depth')
503    local db = node_new(getid(b)) -- dir_node
504    set_attr(db, attr_dir, 
505             new_dir + (is_manual and dir_node_manual or dir_node_auto))
506    set_attr(db, attr_icflag, PROCESSED)
507    set_attr(b, attr_icflag, PROCESSED)
508    tex_set_attr('global', attr_dir, 0)
509    tex_set_attr('global', attr_icflag, 0)
510    setfield(db, 'dir', getfield(b, 'dir'))
511    setfield(db, 'shift', 0)
512    setfield(db, 'width',  info.width(w,h,d))
513    setfield(db, 'height', info.height(w,h,d))
514    setfield(db, 'depth',  info.depth(w,h,d))
515    return db
516 end
517
518 -- 異方向のボックスの処理
519 local make_dir_whatsit, process_dir_node
520 do
521    make_dir_whatsit = function (head, b, new_dir, origin)
522       new_dir = new_dir%dir_math_mod
523       -- head: list head, b: box
524       -- origin: コール元 (for debug)
525       -- return value: (new head), (next of b), (new b), (is_b_dir_node)
526       -- (new b): b か dir_node に被せられた b
527       local bh = getlist(b)
528       local box_dir, dn =  get_box_dir(b, ltjs.list_dir)
529       -- 既に b の中身にあるwhatsit
530
531       if box_dir%dir_math_mod==new_dir then
532          if box_dir>=dir_node_auto then
533             -- dir_node としてカプセル化されている
534             local bc = node_next(node_next(node_next(bh)))
535             local _, dnc = get_box_dir(b, 0)
536             if dnc then -- free all other dir_node
537                Dnode.flush_list(getfield(dnc, 'value'))
538                setfield(dnc, 'value', nil)
539             end
540             set_attr(b, attr_dir, box_dir%dir_math_mod + dir_node_auto)
541             return head, node_next(b), b, true
542          else
543             -- 組方向が一緒 (up to math dir) のボックスなので,何もしなくて良い
544             return head, node_next(b), b, false
545          end
546       else
547          -- 組方向を合わせる必要あり
548          local nh, nb, ret, flag
549          if box_dir>= dir_node_auto then -- unwrap
550             local b_dir
551             head, nb, b, b_dir = unwrap_dir_node(b, head, box_dir)
552             bh = getlist(b)
553             if b_dir%dir_math_mod==new_dir then
554                -- dir_node の中身が周囲の組方向とあっている
555                return head, nb, b, false 
556             else box_dir = b_dir end
557          end
558          box_dir = box_dir%dir_math_mod
559          local db
560          local dnh = getfield(dn, 'value')
561          for x in traverse(dnh) do
562             if has_attr(x, attr_dir)%dir_math_mod == new_dir then
563                setfield(dn, 'value', to_node(node_remove(dnh, x)))
564                db=x; break
565             end
566          end
567          Dnode.flush_list(getfield(dn, 'value'))
568          db = db or create_dir_node(b, box_dir, new_dir, false)
569          local w = getfield(b, 'width')
570          local h = getfield(b, 'height')
571          local d = getfield(b, 'depth')
572          local dn_w = getfield(db, 'width')
573          local dn_h = getfield(db, 'height')
574          local dn_d = getfield(db, 'depth')
575          nh, nb =  insert_before(head, b, db), nil
576          nh, nb = node_remove(nh, b)
577          local db_head, db_tail  = nil
578          for _,v in ipairs(dir_node_aux[box_dir][new_dir][getid(b)]) do
579             local cmd, arg, nn = v[1], v[2]
580             if cmd=='kern' then
581                nn = node_new(id_kern)
582                setfield(nn, 'kern', arg(w, h, d, dn_w, dn_h, dn_d))
583             elseif cmd=='whatsit' then
584                nn = node_new(id_whatsit, arg)
585             elseif cmd=='rotate' then
586                nn = node_new(id_whatsit, sid_matrix)
587                setfield(nn, 'data', arg)
588             elseif cmd=='box' then
589                nn = b; setfield(b, 'next', nil)
590                setfield(nn, 'shift', arg(w, h, d, dn_w, dn_h, dn_d))
591             end
592             if db_head then
593                insert_after(db_head, db_tail, nn)
594                db_tail = nn
595             else
596                db_head, db_tail = nn, nn
597             end
598             setfield(db, 'head', db_head)
599             ret, flag = db, true
600          end
601          return nh, nb, ret, flag
602       end
603    end
604    process_dir_node = function (hd, gc)
605       local x, new_dir = hd, ltjs.list_dir or dir_yoko
606       while x do
607          local xid = getid(x)
608          if (xid==id_hlist and has_attr(x, attr_icflag)%PROCESSED_BEGIN_FLAG~=PACKED) 
609          or xid==id_vlist then
610             hd, x = make_dir_whatsit(hd, x, new_dir, 'process_dir_node:' .. gc)
611          else
612             x = node_next(x)
613          end
614       end
615       return hd
616    end
617
618    -- lastbox
619    local node_prev = (Dnode~=node) and Dnode.getprev or node.prev
620    local function lastbox_hook()
621       start_time_measure('box_primitive_hook')
622       local bn = tex_nest[tex_nest.ptr].tail
623       if bn then
624          local b, head = to_direct(bn), to_direct(tex_nest[tex_nest.ptr].head)
625          local bid = getid(b)
626          if bid==id_hlist or bid==id_vlist then
627             local box_dir =  get_box_dir(b, 0)
628             if box_dir>= dir_node_auto then -- unwrap dir_node
629                local p = node_prev(b)
630                local dummy1, dummy2, nb = unwrap_dir_node(b, nil, box_dir)
631                setfield(p, 'next', nb);  tex_nest[tex_nest.ptr].tail = to_node(nb)
632                setfield(b, 'next', nil); setfield(b, 'head', nil)
633                node_free(b); b = nb
634             end
635             local _, wh =  get_box_dir(b, 0) -- clean dir_node attached to the box
636             if wh then
637                Dnode.flush_list(getfield('value', wh))
638                setfield(wh, 'value', nil)
639             end
640          end
641       end
642       stop_time_measure('box_primitive_hook')
643    end
644
645    luatexja.direction.make_dir_whatsit = make_dir_whatsit
646    luatexja.direction.lastbox_hook = lastbox_hook
647 end
648
649 -- \wd, \ht, \dp の代わり
650 do
651    local getbox, setdimen = tex.getbox, tex.setdimen
652    local function get_box_dim_common(key, s, l_dir)
653       -- s: not dir_node.
654       local s_dir, wh = get_box_dir(s, dir_yoko)
655       s_dir = s_dir%dir_math_mod
656       if s_dir ~= l_dir then
657          local not_found = true
658          for x in traverse(getfield(wh, 'value')) do
659             if l_dir == has_attr(x, attr_dir)%dir_node_auto then
660                setdimen('ltj@tempdima', getfield(x, key))
661                not_found = false; break
662             end
663          end
664          if not_found then
665             local w = getfield(s, 'width')
666             local h = getfield(s, 'height')
667             local d = getfield(s, 'depth')
668             setdimen('ltj@tempdima', 
669                          dir_node_aux[s_dir][l_dir][key](w,h,d))
670          end
671       else
672          setdimen('ltj@tempdima', getfield(s, key))
673       end
674    end
675    local function get_box_dim(key, n)
676       local gt = tex.globaldefs; tex.globaldefs = 0
677       local s = getbox(n)
678       if s then
679          local l_dir = (get_dir_count())%dir_math_mod
680          s = to_direct(s)
681          local b_dir = get_box_dir(s,dir_yoko)
682          if b_dir<dir_node_auto then
683             get_box_dim_common(key, s, l_dir)
684          elseif b_dir%dir_math_mod==l_dir then
685             setdimen('ltj@tempdima', getfield(s, key))
686          else
687             get_box_dim_common(key, 
688                                node_next(node_next(node_next(getlist(s)))), l_dir)
689          end
690       else
691          setdimen('ltj@tempdima', 0)
692       end
693       tex.globaldefs = gt
694    end
695    luatexja.direction.get_box_dim = get_box_dim
696
697    -- return value: (changed dimen of box itself?)
698    local function set_box_dim_common(key, s, l_dir)
699       local s_dir, wh = get_box_dir(s, dir_yoko)
700       s_dir = s_dir%dir_math_mod
701       if s_dir ~= l_dir then
702          if not wh then
703             wh = create_dir_whatsit(getlist(s), 'set_box_dim', s_dir)
704             setfield(s, 'head', wh)
705          end
706          local db
707          local dnh = getfield(wh, 'value')
708          for x in traverse(dnh) do
709             if has_attr(x, attr_dir)%dir_node_auto==l_dir then
710                db = x; break
711             end
712          end
713          if not db then
714             db = create_dir_node(s, s_dir, l_dir, true)
715             setfield(db, 'next', dnh)
716             setfield(wh, 'value',to_node(db))
717          end
718          setfield(db, key, tex.getdimen('ltj@tempdima'))
719          return false
720       else
721          setfield(s, key, tex.getdimen('ltj@tempdima'))
722          if wh then
723             -- change dimension of dir_nodes which are created "automatically"
724                local bw, bh, bd 
725                   = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
726             for x in traverse(getfield(wh, 'value')) do
727                local x_dir = has_attr(x, attr_dir)
728                if x_dir<dir_node_manual then
729                   local info = dir_node_aux[s_dir][x_dir%dir_node_auto]
730                   setfield(x, 'width',  info.width(bw,bh,bd))
731                   setfield(x, 'height', info.height(bw,bh,bd))
732                   setfield(x, 'depth',  info.depth(bw,bh,bd))
733                end
734             end
735          end
736          return true
737       end
738    end
739    local function set_box_dim(key)
740       local n = tex_getcount('ltj@tempcnta')
741       local s = getbox(n)
742       if s then
743          local l_dir = (get_dir_count())%dir_math_mod
744          s = to_direct(s)
745          local b_dir = get_box_dir(s,dir_yoko)
746          if b_dir<dir_node_auto then
747             set_box_dim_common(key, s, l_dir)
748          elseif b_dir%dir_math_mod == l_dir then
749             -- s is dir_node
750             setfield(s, key, tex.getdimen('ltj@tempdima'))
751             if b_dir<dir_node_manual then
752                set_attr(s, attr_dir, b_dir%dir_node_auto + dir_node_manual)
753             end
754             -- re-calculate shift and kern (TODO)
755             local sid, sl = getid(s), getlist(s)
756             local b = node_next(node_next(node_next(sl))) -- 本来の box
757             local info = dir_node_aux[get_box_dir(b,dir_yoko)%dir_math_mod][b_dir%dir_node_auto]
758             local bw, bh, bd 
759                = getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth')
760             local sw, sh, sd 
761                = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
762             -- re-calculate shift and kern
763             for i,v in ipairs(info[sid]) do 
764                if getid(sl)==id_kern then
765                   setfield(sl, 'kern', v[2](bw,bh,bd,sw,sh,sd) )
766                elseif getid(sl)==sid then
767                   setfield(sl, 'shift', v[2](bw,bh,bd,sw,sh,sd) )
768                end
769                sl = node_next(sl)
770             end
771          else
772             local sid, sl = getid(s), getlist(s)
773             local b = node_next(node_next(node_next(sl))) -- 本来の box
774             local info = dir_node_aux[get_box_dir(b,dir_yoko)%dir_math_mod][b_dir%dir_node_auto]
775             local bw, bh, bd 
776                = getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth')
777             local sw, sh, sd 
778                = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
779             if set_box_dim_common(key, b, l_dir) then
780                -- re-calculate shift and kern
781                for i,v in ipairs(info[sid]) do 
782                   if getid(sl)==id_kern then
783                      setfield(sl, 'kern', v[2](bw,bh,bd,sw,sh,sd) )
784                   elseif getid(sl)==sid then
785                      setfield(sl, 'shift', v[2](bw,bh,bd,sw,sh,sd) )
786                   end
787                   sl = node_next(sl)
788                end
789                -- re-calculate dimension of s, if s is created "automatically"
790                if b_dir<dir_node_manual then
791                   setfield(s, 'width',  info.width(bw,bh,bd))
792                   setfield(s, 'height', info.height(bw,bh,bd))
793                   setfield(s, 'depth',  info.depth(bw,bh,bd))
794                end
795             end
796          end
797       end
798    end
799    luatexja.direction.set_box_dim = set_box_dim
800 end
801
802 do
803    local getbox = tex.getbox
804    local function get_register_dir(n)
805       local s = getbox(n)
806       if s then
807          s = to_direct(s)
808          local b_dir = get_box_dir(s, dir_yoko)
809          if b_dir<dir_node_auto then
810             return b_dir
811          else
812             local b_dir = get_box_dir(
813                node_next(node_next(node_next(getlist(s)))), dir_yoko)
814             return b_dir
815          end
816       else
817          return 0
818       end
819    end
820    luatexja.direction.get_register_dir = get_register_dir
821 end
822
823 do
824    local getbox, setbox, copy_list = tex.getbox, tex.setbox, Dnode.copy_list
825    -- raise, lower
826    function luatexja.direction.raise_box()
827       start_time_measure('box_primitive_hook')
828       local list_dir = get_dir_count()
829       local s = getbox('ltj@afbox')
830       if s then
831          local sd = to_direct(s)
832          local box_dir = get_box_dir(sd, dir_yoko)
833          if box_dir%dir_math_mod ~= list_dir then
834             setbox(
835                'ltj@afbox', 
836                to_node(
837                   copy_list(make_dir_whatsit(sd, sd, list_dir, 'box_move'))
838                   -- without copy_list, we get a segfault
839                )
840             )
841          end
842       end
843       stop_time_measure('box_primitive_hook')
844    end
845 end
846
847 -- 縦書き用字形への変換テーブル
848 local font_vert_table = {} -- key: fontnumber
849 do
850    local font_vert_basename = {} -- key: basename
851    local function add_feature_table(tname, src, dest)
852       for i,v in pairs(src) do
853          if type(v.slookups)=='table' then
854             local s = v.slookups[tname]
855             if s and not dest[i] then
856                dest[i] = s
857             end
858          end
859       end
860    end
861
862    local function prepare_vert_data(n, id)
863       -- test if already loaded
864       if type(id)=='number' then -- sometimes id is an integer
865          font_vert_table[n] = font_vert_table[id]; return
866       elseif (not id) or font_vert_table[n]  then return
867       end
868       local fname = id.filename
869       local bname = file.basename(fname)
870       if not fname then
871          font_vert_table[n] = {}; return
872       elseif font_vert_basename[bname] then
873          font_vert_table[n] = font_vert_basename[bname]; return
874       end
875       local vtable = {}
876       local a = id.resources.sequences
877       if a then
878          local s = id.shared.rawdata.descriptions
879          for i,v in pairs(a) do
880             if v.features.vert or v.features.vrt2 then
881                add_feature_table(v.subtables[1], s, vtable)
882             end
883          end
884       end
885       font_vert_basename[bname] = vtable
886       font_vert_table[n] = vtable
887    end
888    -- 縦書き用字形への変換
889    function luatexja.direction.get_vert_glyph(n, chr)
890       local fn = font_vert_table[n]
891       return fn and fn[chr] or chr
892    end
893    luatexbase.add_to_callback('luatexja.define_font',
894                               function (res, name, size, id)
895                                  prepare_vert_data(id, res)
896                               end,
897                               'prepare_vert_data', 1)
898
899    local function a (n, dat) font_vert_table[n] = dat end
900    luatexja.rmlgbm.vert_addfunc = a
901
902 end
903
904 -- PACKED の hbox から文字を取り出す
905 -- luatexja.jfmglue.check_box などで使用
906 do
907    local function glyph_from_packed(h)
908       local b = getlist(h)
909       return (getid(b)==id_kern) 
910          and node_next(node_next(node_next(node_next(b)))) or b
911    end
912    luatexja.direction.glyph_from_packed = glyph_from_packed
913 end
914
915 -- adjust and insertion
916 local id_adjust = node.id('adjust')
917 function luatexja.direction.check_adjust_direction()
918    start_time_measure('box_primitive_hook')
919    local list_dir = get_adjust_dir_count()
920    local a = tex_nest[tex_nest.ptr].tail
921    local ad = to_direct(a)
922    if a and getid(ad)==id_adjust then
923       local adj_dir = get_box_dir(ad)
924       if list_dir~=adj_dir then
925          ltjb.package_error(
926                  'luatexja',
927                  'Direction Incompatible',
928                  "\\vadjust's argument and outer vlist must have same direction.")
929          Dnode.last_node()
930       end
931    end
932    stop_time_measure('box_primitive_hook')
933 end
934
935 -- vsplit
936 do
937    local split_dir_whatsit
938    local function dir_adjust_vpack(h, gc)
939       start_time_measure('direction_vpack')
940       local hd = to_direct(h)
941       if gc=='split_keep' then
942          -- supply dir_whatsit
943          hd = create_dir_whatsit_vbox(hd, gc)
944          split_dir_whatsit = hd
945       elseif gc=='split_off'  then
946          local bh=hd
947          for i=1,2 do
948             if bh and getid(bh)==id_whatsit
949             and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
950                ltjs.list_dir  = has_attr(bh, attr_dir); break
951             end
952             bh = node_next(bh)
953          end
954          if split_dir_whatsit then
955             -- adjust direction of 'split_keep'
956             set_attr(split_dir_whatsit, attr_dir, ltjs.list_dir)
957          end
958          split_dir_whatsit=nil
959       elseif gc=='preamble' then
960          split_dir_whatsit=nil
961       else
962          adjust_badness(hd)
963          hd = process_dir_node(create_dir_whatsit_vbox(hd, gc), gc)
964          split_dir_whatsit=nil
965       end
966       stop_time_measure('direction_vpack')
967       return to_node(hd)
968    end
969    luatexbase.add_to_callback('vpack_filter',
970                               dir_adjust_vpack,
971                               'ltj.direction', 10000)
972 end
973
974 do
975    -- supply direction whatsit to the main vertical list "of the next page"
976    local function dir_adjust_pre_output(h, gc)
977       return to_node(create_dir_whatsit_vbox(to_direct(h), gc))
978    end
979    luatexbase.add_to_callback('pre_output_filter',
980                               dir_adjust_pre_output,
981                               'ltj.direction', 10000)
982
983    function luatexja.direction.remove_end_whatsit()
984       local h=tex.lists.page_head
985       if (not h.next) and
986          h.id==id_whatsit and h.subtype==sid_user and
987          h.user_id == DIR then
988             tex.lists.page_head = nil
989             node.free(h)
990       end
991    end
992 end
993
994 -- 
995 do
996    local function dir_adjust_buildpage(info)
997       if info=='box' then
998          local head = to_direct(tex.lists.contrib_head)
999          local nb
1000          if head then
1001             head, _, nb
1002                = make_dir_whatsit(head, 
1003                                   node_tail(head),
1004                                   get_dir_count(), 
1005                                   'buildpage')
1006             tex.lists.contrib_head = to_node(head)
1007          end
1008       end
1009    end
1010    luatexbase.add_to_callback('buildpage_filter',
1011                               dir_adjust_buildpage,
1012                               'ltj.direction', 10000)
1013 end