; draw.tt - a simple drawing application
; -------
to black
  output 0
  end
to white
  output 7
  end

to north
  output 0
  end

to buttonFontSiz
  output 14
  end
to buttonWidth
  output 65
  end
to buttonHeight
  output 25
  end
to buttonGap
  output 10
  end
to buttonsY
  output sum 10 minus quotient canvasheight 2
  end

to clrButtonX
  output sum 10 minus quotient canvaswidth 2
  end
to pudButtonX
  output sum clrButtonX sum buttonWidth buttonGap
  end

to coloredRectAt :x :y :height :width :color
  setpencolor :color setheading north setpensize :width
  if equal? remainder :width 2 1 [setpensize difference :width 1]
  penup setxy (sum :x quotient :width 2) :y pendown
  forward :height
  if equal? remainder :width 2 1 [pu setxy (sum :x :width) :y pd setps 1 fd :height]
  end

to frameAt :x :y :height :width :penSiz
  setpensize :penSiz setpencolor black
  penup setxy :x :y pendown setheading north
  repeat 2 [ forward :height right 90 forward :width right 90 ]
  end

to drawButtonAt :x :y :text
  coloredRectAt :x :y buttonHeight buttonWidth white
  setpencolor black
  frameAt :x :y buttonHeight buttonWidth 2
  penup setxy (sum :x 4) (sum :y 8) pendown
  setlabelheight buttonFontSiz label :text
  end

; output "true if latest mouseclick was inside the specified rectangle
; output "false if not
to mouseInRect? :x :y :height :width
  if less? mousex :x [output "false]
  if less? mousey :y [output "false]
  if greater? mousex sum :x :width [output "false]
  if greater? mousey sum :y :height [output "false]
  output "true
  end

to liftPen
  drawButtonAt pudButtonX buttonsY "PenDown
  penup setpencolor white
  end
to lowerPen
  drawButtonAt pudButtonX buttonsY "PenUp
  pendown setpencolor black
  end
to flipPenState
  ifelse pendown? [liftPen] [lowerPen]
  end

to init
  clean
  drawButtonAt clrButtonX buttonsY "Clear
  liftPen
  home
  end

to mouseclick
  if mouseInRect? clrButtonX buttonsY buttonHeight buttonWidth [init stop]
  if mouseInRect? pudButtonX buttonsY buttonHeight buttonWidth [flipPenState stop]
  setxy mousex mousey
  end

init