#!/usr/local/bin/ruby
# by YOSHIDA Kazuhiro (moriq@moriq.com)
# modified by KUMAGAI Hidetake (ggb03124@nifty.ne.jp)

module RGUI
  class Vbox < Widget
    include RGUI

    attr_accessor :space, :left, :top, :width, :height

    def space=(v)
      @space = v if v >= 0
    end

    def initialize(homo=false,space=0,fill=true,vdir=:n,hdir=:w)
      super
      @homo = homo
      @space = space
      @fill = fill
      @vdir = vdir
      @hdir = hdir
    end

    def layout
      return if @children.empty?
      homonize if @homo
      h = max 0, @height - @space
      len = 0 ; @children.each{|c| len+= c.base_height }
      len = max 1, len
      if @fill
        @children.each do |c|
          c.width  = @width
          c.height = max 0, c.base_height*h/len - @space
        end
        left = @left
        space = @space
      else
        sum_height = 0
        max_width = 0
        @children.each do |c|
          sum_height += c.height
          max_width = [max_width , c.width].max
        end
        left = [(@width - max_width)/2 , 0].max + @left
        space = (@height - sum_height)/(@children.size + 1)
      end
      top = (h % @children.size) / 2 + space
      top = @height - top if @vdir == :s
      @children.each do |c|
        case @hdir
        when :w ; c.left = left
        when :e ; c.left = left+@width-c.width
        end
        case @vdir
        when :n ; c.top = @top+top          ;  top+= space + c.height
        when :s ; c.top = @top+top-c.height ;  top-= space + c.height
        end
        c.layout if defined? c.layout
      end
    end

  end
end
