drawing area & events

Basile STARYNKEVITCH <[email protected]> Thu, 07 Jan 2010 21:59:07 +0100
Newsgroups gmane.comp.lang.ocaml.lib.gtk
Message-ID <[email protected]>
Hello All,

I am fluent in Ocaml, but new to LablGtk (and still scared of OCaml object system).

As an exercise, I want to make a drawing area which captures every mouse click and make a polygon of them, until any key 
is pressed on the keyboard. So I coded the following example.

#####################################

(***
      file testdrawar.ml to compile with:
      /usr/bin/ocamlopt -I +lablgtk2 -g -annot  lablgtk.cmxa gtkInit.cmx testdrawar.ml -o testdrawar
***)

let pointslist = ref ([20,60; 20,40; 40,70] : (int * int) list);;

let drawfun (drawar : GMisc.drawing_area) =
   Printf.eprintf "drawfun %d points\n%!" (List.length !pointslist);
   let drawindow =
     let dmisc = drawar#misc in  dmisc#window
   in
   let drawing =
     new GDraw.drawable drawindow
   in
     drawing#polygon ~filled:false !pointslist;
     ()
;;

let buttonfun bev =
   let butnum = GdkEvent.Button.button bev
   and x = (int_of_float (GdkEvent.Button.x bev))
   and y = (int_of_float (GdkEvent.Button.x bev))
   in
     Printf.eprintf "buttonfun butnum=%d x=%d y=%d\n%!" butnum x y;
     pointslist := (x,y)::!pointslist;
     ()
;;

let keyfun kev =
   let strk = GdkEvent.Key.string kev in
     Printf.eprintf "keyfun %S\n%!" strk;
     pointslist := []
;;


let topwin = GWindow.window ~title: "testdrawar" ~width: 400 ~height: 300 () in
let drawar = GMisc.drawing_area ~packing: topwin#add () in
   ignore (drawar#event#add [ `BUTTON_PRESS; `KEY_PRESS]);
   ignore (drawar#event#connect#button_press
             ~callback: (fun bev -> buttonfun bev; drawfun drawar; true));
   ignore (drawar#event#connect#key_press
             ~callback: (fun kev -> keyfun kev; drawfun drawar; true));
   ignore (drawar#event#connect#expose ~callback: (fun ev -> drawfun drawar; true));
   let dmisc = drawar#misc in dmisc#realize ();
   topwin#show ()
;;

GMain.Main.main ();;

(*eof*)

#############################################

unfortunately, the code above is incorrect:

For some reason, keyboard events are not caught properly. Should I ask for focus?

For some reason, the mouse click coordinates are not correct in the drawing area. I should make some conversion (how to 
do that)?

Any help is appreciated. For the mightly LablGtk contributors, feel free to add a similar example to the documentation.
It would help a lot.

Happy New Year 2010 (and Merry Christmas to those celebrating it today, e.g. in Russia).

Regards.

-- 
Basile STARYNKEVITCH         http://starynkevitch.net/Basile/
email: basile<at>starynkevitch<dot>net mobile: +33 6 8501 2359
8, rue de la Faiencerie, 92340 Bourg La Reine, France
*** opinions {are only mines, sont seulement les miennes} ***