#include once "inc/iup_draw.bi"
#include once "inc/iupimglib.bi"

dim as ubyte img_x_bits(...) = { _
  1,2,3,3,3,3,3,3,3,2,1, _
  2,1,2,3,3,3,3,3,2,1,2, _
  3,2,1,2,3,3,3,2,1,2,3, _
  3,3,2,1,2,3,2,1,2,3,3, _
  3,3,3,2,1,2,1,2,3,3,3, _
  3,3,3,3,2,1,2,3,3,3,3, _
  3,3,3,2,1,2,1,2,3,3,3, _
  3,3,2,1,2,3,2,1,2,3,3, _
  3,2,1,2,3,3,3,2,1,2,3, _
  2,1,2,3,3,3,3,3,2,1,2, _
  1,2,3,3,3,3,3,3,3,2,1}

sub _init_ constructor
  IupOpen(0,0)
  IupImageLibOpen()
end sub

sub _exit_ destructor
  IupClose()
end sub


' redraw canvas (create DrawCanvas on the fly)
function canvas_action_cb cdecl (self as IHandle ptr) as integer
  ' create offscreen image 
  dim as IDrawCanvas ptr dc = iupDrawCreateCanvas(self) 
  if dc then
    dim as integer w,h,imgw,imgh
    ' get current size
    iupDrawGetSize(dc,@w,@h)
    if w<1 then w=1
    if h<1 then h=1
    
    dim as single rStep = 255.0 / w
    dim as single gStep = 255.0 / h
    ' black background
    iupDrawRectangle(dc,0,0,w-1,h-1, 0,0,0, IUP_DRAW_FILL)
    
    ' red hor. lines
    for x as integer= 0 to w-1 step 8
      iupDrawLine(dc, _
                  x,0,x,h-1, _
                  x*rStep,0,0, _
                  IUP_DRAW_STROKE)
    next
    ' green ver. lines
    for y as integer= 0 to h-1 step 8
      iupDrawLine(dc, _
                  0,y,w-1,y, _
                  0,y*gStep,0, _
                  IUP_DRAW_STROKE)
    next
    
    ' draw text
    for i as integer=1 to 10
      iupDrawText(dc,"Times bold 12",13,rnd*w,rnd*h,rnd*255,rnd*255,rnd*255,"TIMES_BOLD_12")
    next  

    ' draw a user defined image 
    iupDrawImage(dc,"img_x",0, w\2-6,h\2-6,@imgw,@imgh)

    ' draw a predefined IUP image 
    iupDrawImage(dc,ImgNames(IUP_TECGRAF),0, 0,0,@imgw,@imgh)

    ' show the offscreen image 
    iupDrawFlush(dc)

    ' free the offscreen image
    iupDrawKillCanvas(dc)
  end if  

  return IUP_DEFAULT
end function


'
' main
'
dim as IHandle ptr canvas = IupCanvas(NULL)
IupSetCallback(canvas, "ACTION",@canvas_action_cb)
dim as IHandle ptr img_x = IupImage ( 11, 11, @img_x_bits(0) )
IupSetHandle ( "img_x", img_x )
IupSetAttribute ( img_x, "1", "0 1 0")
IupSetAttribute ( img_x, "2", "255 0 0")
IupSetAttribute ( img_x, "3", "0 0 0")

dim as IHandle ptr dialog=IupDialog(canvas)
IupSetAttribute(dialog, "RASTERSIZE", "320x240")
IupSetAttribute(dialog, "TITLE", "resize me ...")

IupShow(dialog)

IupMainLoop()