picker.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use gdk;
  2. use gtk::{
  3. self,
  4. WidgetExt
  5. };
  6. use std::cell::RefCell;
  7. use std::rc::Rc;
  8. pub struct Picker {
  9. pub canvas: gtk::DrawingArea,
  10. pub mouse_loc: Rc<RefCell<Option<(i32, i32)>>>,
  11. }
  12. impl Picker {
  13. pub fn new() -> Picker {
  14. let canvas = gtk::DrawingArea::new();
  15. let mouse_loc = Rc::new(RefCell::new(Some((2, 2))));
  16. let reader_mouse = mouse_loc.clone();
  17. let writer_mouse = mouse_loc.clone();
  18. canvas.connect_draw(move |cv, ctx| {
  19. let w = cv.get_allocated_width();
  20. let h = cv.get_allocated_height();
  21. ctx.set_source_rgb(1.0, 1.0, 1.0);
  22. ctx.rectangle(0.0, 0.0, w as f64, h as f64);
  23. ctx.fill();
  24. reader_mouse.borrow().map(|(x, y)| {
  25. ctx.set_source_rgb(0.9, 0.9, 0.9);
  26. ctx.rectangle(
  27. x as f64 * 32.0,
  28. y as f64 * 32.0,
  29. 32.0,
  30. 32.0,
  31. );
  32. ctx.fill();
  33. });
  34. gtk::Inhibit(false)
  35. });
  36. canvas.connect_motion_notify_event(move |cv, motion| {
  37. let (x, y) = motion.get_position();
  38. *writer_mouse.borrow_mut() =
  39. Some((x as i32 / 32, y as i32 / 32));
  40. cv.queue_draw();
  41. gtk::Inhibit(false)
  42. });
  43. canvas.add_events(gdk::POINTER_MOTION_MASK.bits() as i32);
  44. Picker {
  45. canvas,
  46. mouse_loc,
  47. }
  48. }
  49. }