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