gdritter repos palladio / a012509
Add canvas submodule Getty Ritter 6 years ago
1 changed file(s) with 62 addition(s) and 0 deletion(s). Collapse all Expand all
1 use gdk;
2 use gtk::{
3 self,
4 WidgetExt
5 };
6 use std::cell::RefCell;
7 use std::rc::Rc;
8
9 pub struct GridCanvas {
10 pub canvas: gtk::DrawingArea,
11 pub mouse_loc: Rc<RefCell<Option<(i32, i32)>>>,
12 }
13
14 impl GridCanvas {
15 pub fn new() -> GridCanvas {
16 let canvas = gtk::DrawingArea::new();
17 let mouse_loc = Rc::new(RefCell::new(Some((2, 2))));
18 let reader_mouse = mouse_loc.clone();
19 let writer_mouse = mouse_loc.clone();
20
21 canvas.connect_draw(move |cv, ctx| {
22 let w = cv.get_allocated_width();
23 let h = cv.get_allocated_height();
24 ctx.set_source_rgb(1.0, 1.0, 1.0);
25 ctx.rectangle(0.0, 0.0, w as f64, h as f64);
26 ctx.fill();
27
28 ctx.set_source_rgb(0.9, 0.9, 0.9);
29 reader_mouse.borrow().map(|(x, y)| {
30 ctx.rectangle(x as f64 * 32.0, y as f64 * 32.0, 32.0, 32.0);
31 ctx.fill();
32 });
33
34 ctx.set_source_rgb(0.8, 0.8, 0.8);
35 for x in 0..((w / 32) + 1) {
36 ctx.move_to(x as f64 * 32.0, 0.0);
37 ctx.line_to(x as f64 * 32.0, h as f64);
38 ctx.stroke();
39 }
40 for y in 0..((h / 32) + 1) {
41 ctx.move_to(0.0, y as f64 * 32.0);
42 ctx.line_to(w as f64, y as f64 * 32.0);
43 ctx.stroke();
44 }
45 gtk::Inhibit(false)
46 });
47
48 canvas.connect_motion_notify_event(move |cv, motion| {
49 let (x, y) = motion.get_position();
50 *writer_mouse.borrow_mut() = Some((x as i32 / 32, y as i32 / 32));
51 cv.queue_draw();
52 gtk::Inhibit(false)
53 });
54
55 canvas.add_events(gdk::POINTER_MOTION_MASK.bits() as i32);
56
57 GridCanvas {
58 canvas,
59 mouse_loc,
60 }
61 }
62 }