OSDN Git Service

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