/*
 * IupCanvas example
 * Description : Creates a IUP canvas and uses CD to draw on it
 *      Remark : IUP must be linked to the CD library
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "iup.h"
#include "cd.h"
#include "cdiup.h"


static cdCanvas *cdcanvas = NULL;
int draw = 0;

int button_cb(Ihandle* self, int but, int press, int x, int y)
{
  if (but == IUP_BUTTON1 && press)
  {
    cdCanvasUpdateYAxis(cdcanvas, &y);
    cdCanvasPixel(cdcanvas, x, y, CD_BLUE);
    draw = 1;
  }
  else
  {
    cdCanvasClear(cdcanvas);
    draw = 0;
  }

  return IUP_DEFAULT;
}

int motion_cb(Ihandle* self, int x, int y)
{
  if (draw)
  {
    cdCanvasUpdateYAxis(cdcanvas, &y);
    cdCanvasPixel(cdcanvas, x, y, CD_BLUE);
  }

  return IUP_DEFAULT;
}

int redraw_cb( Ihandle *self, float x, float y )
{
  cdCanvasActivate(cdcanvas);
  cdCanvasClear(cdcanvas);
  cdCanvasForeground(cdcanvas, CD_BLUE);
  cdCanvasBox(cdcanvas, 0, 100, 0, 100);
  return IUP_DEFAULT;
}


int main(int argc, char **argv)
{
  Ihandle *dlg, *cnvs;
  IupOpen(&argc, &argv);

  cnvs = IupCanvas( NULL );
  IupSetCallback(cnvs, "ACTION",( Icallback )redraw_cb );
  IupSetAttribute(cnvs, "SIZE", "300x100");
  IupSetCallback(cnvs, "BUTTON_CB",(Icallback)button_cb);
  IupSetCallback(cnvs, "MOTION_CB",(Icallback)motion_cb);


  dlg = IupDialog( IupVbox( cnvs, NULL ) );
  IupSetAttribute( dlg, "TITLE", "IupCanvas + Canvas Draw" );
  IupSetAttribute(dlg, "MARGIN", "10x10");
  IupMap( dlg );

  cdcanvas = cdCreateCanvas( CD_IUP, cnvs );
  cdCanvasForeground(cdcanvas, CD_BLUE);

  IupShowXY( dlg, IUP_CENTER, IUP_CENTER );
  IupMainLoop();
  IupClose();
  return EXIT_SUCCESS;
}
