OSDN Git Service

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