OSDN Git Service

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