#! ruby

# cf:
# Delphi4 プログラミングバイブル p.544
# 12.4.1. DBGrid のペイント

require 'phi'
include Phi
require 'rdb'
include RDB

form = Form.new

table = Table.new
table.database_name = 'DBDEMOS'
table.table_name = 'biolife.db'
table.active = true

def table.before_insert
  Phi.abort
end

data_source = DataSource.new table

grid = DBGrid.new(form, :grid)
grid.align = Phi::AL_CLIENT
grid.data_source = data_source
grid.font.style = [Phi::FS_BOLD]
grid.default_drawing = false

columns = grid.columns
p columns.count		##	8
p columns[0]		##	#<RDB::Column:0xf66310>
p columns[1]

    def columns.status_hash= (hash)
      (1..1).each{
        ok = true
        self.each{|c|
p c.field_name
p         data = hash[c.field_name]
          next unless data
          next if data == [c.index, c.width]
          c.index = data[0]
          c.width = data[1]
          ok = false
          break
        }
        break if ok
      }
    end

columns.status_hash= ({'Common_Name'=>[0,100]})

def grid.on_draw_column_cell(rect, col, column, state)
  if column.field.data_type == RDB::FT_GRAPHIC
    bmp = Bitmap.new
    bmp.assign column.field
    canvas.stretch_draw rect, bmp
  else
    GC.start
    canvas.font.color =
    if column.field.field_name == 'Length (cm)' and column.field.to_i > 100
      Phi::CL_RED
    elsif state.include? Phi::GD_SELECTED
      Phi::CL_WHITE
    else
      column.font.color
    end
    canvas.text_rect(rect, rect.left, rect.top, column.field.to_s)
  end
  if state.include? Phi::GD_FOCUSED
    canvas.draw_focus_rect(rect)
  end
end
nav = DBNavigator.new(form, :nav)
nav.align = Phi::AL_TOP
nav.data_source = data_source

form.show

Phi.mainloop

#table.close
=begin
#= GC check
def print_instance_count_of(m)
  c = 0
  ObjectSpace.each_object(m) { c+=1 }
  print "instance count of #{m}: #{c}\n"
end
alias :pico :print_instance_count_of

print "prev GC\n"
[Font, Canvas, Form, Table, DataSource, DBGrid, Bitmap].each { |m| pico m }

GC.start

print "post GC\n"
[Font, Canvas, Form, Table, DataSource, DBGrid, Bitmap].each { |m| pico m }

print ":done\n"
=end
