#! ruby

# cf:
# Delphi4 プログラミングバイブル p.293
# 6.7.4. マウスを使ったドラッグと描画

require 'phi'
include Phi

form = Form.new

class << form
  attr :dragging, true
  attr :rect, true
end
form.rect = Rect.new

def form.on_mouse_down(btn,sft,x,y)
  p = self
  case btn
  when Phi::MB_LEFT
    p.dragging = true
    p.rect.left = x
    p.rect.top = y
    p.rect.bottom = p.rect.top
    p.rect.right = p.rect.left
    canvas.draw_focus_rect p.rect
  end
end

def form.on_mouse_move(sft,x,y)
  p = self
  self.caption = sprintf 'マウス座標 x=%d y=%d', x,y
  if p.dragging
    canvas.draw_focus_rect p.rect
    if p.rect.left < x then p.rect.right  = x else p.rect.left = x end
    if p.rect.top  < y then p.rect.bottom = y else p.rect.top  = y end
    canvas.draw_focus_rect p.rect
  else
    canvas[x,y] = Phi::CL_YELLOW if sft.include? Phi::SS_SHIFT
  end
end

def form.on_mouse_up(btn,sft,x,y)
  p = self
  if p.dragging
    p.dragging = false
    invalidate
  end
end

def form.on_paint
  p = self
  canvas.rectangle p.rect
end

form.show

Phi.mainloop
