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