#! 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

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

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
    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

#= 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"
