1use sfml::{graphics::*, system::*, window::*, SfResult};
2
3include!("../example_common.rs");
4
5fn main() -> SfResult<()> {
6 example_ensure_right_working_dir();
7
8 let mut window = RenderWindow::new(
9 (800, 600),
10 "Mouse events",
11 Style::CLOSE,
12 &Default::default(),
13 )?;
14 window.set_mouse_cursor_visible(false);
15 window.set_vertical_sync_enabled(true);
16
17 let font = Font::from_file("sansation.ttf")?;
18 let mut circle = CircleShape::new(4., 30);
19 let mut texts: Vec<Text> = Vec::new();
20 let mut mp_text = Text::new("", &font, 14);
21 let mut cursor_visible = false;
22 let mut grabbed = false;
23 macro_rules! push_text {
24 ($x:expr, $y:expr, $fmt:expr, $($arg:tt)*) => {
25 let mut text = Text::new(&format!($fmt, $($arg)*), &font, 14);
26 text.set_position(($x as f32, $y as f32));
27 texts.push(text);
28 }
29 }
30
31 'mainloop: loop {
32 while let Some(ev) = window.poll_event() {
33 match ev {
34 Event::Closed => break 'mainloop,
35 Event::MouseWheelScrolled { wheel, delta, x, y } => {
36 push_text!(x, y, "Scroll: {:?}, {}, {}, {}", wheel, delta, x, y);
37 }
38 Event::MouseButtonPressed { button, x, y } => {
39 push_text!(x, y, "Press: {:?}, {}, {}", button, x, y);
40 }
41 Event::MouseButtonReleased { button, x, y } => {
42 push_text!(x, y, "Release: {:?}, {}, {}", button, x, y);
43 }
44 Event::KeyPressed { code, .. } => {
45 if code == Key::W {
46 window.set_mouse_position(Vector2i::new(400, 300));
47 } else if code == Key::D {
48 let dm = VideoMode::desktop_mode();
49 let center = Vector2i::new(dm.width as i32 / 2, dm.height as i32 / 2);
50 mouse::set_desktop_position(center);
51 } else if code == Key::V {
52 cursor_visible = !cursor_visible;
53 window.set_mouse_cursor_visible(cursor_visible);
54 } else if code == Key::G {
55 grabbed = !grabbed;
56 window.set_mouse_cursor_grabbed(grabbed);
57 }
58 }
59 _ => {}
60 }
61 }
62
63 let mp = window.mouse_position();
64 let dmp = mouse::desktop_position();
65 let cur_vis_msg = if cursor_visible {
66 "visible"
67 } else {
68 "invisible"
69 };
70 let grab_msg = if grabbed { "grabbed" } else { "not grabbed" };
71 mp_text.set_string(&format!(
72 "x: {}, y: {} (Window)\n\
73 x: {}, y: {} (Desktop)\n\
74 [{cur_vis_msg}] [{grab_msg}] ('V'/'G') to toggle\n\
75 'W' to center mouse on window\n\
76 'D' to center mouse on desktop",
77 mp.x, mp.y, dmp.x, dmp.y
78 ));
79
80 circle.set_position((mp.x as f32, mp.y as f32));
81
82 window.clear(Color::BLACK);
83 for i in (0..texts.len()).rev() {
85 for j in (0..i).rev() {
86 if let Some(intersect) = texts[i]
87 .global_bounds()
88 .intersection(&texts[j].global_bounds())
89 {
90 texts[j].move_((0., -intersect.height));
91 }
92 }
93 }
94 texts.retain(|txt| txt.fill_color().a > 0);
95 for txt in &mut texts {
96 let mut color = txt.fill_color();
97 color.a -= 1;
98 txt.set_fill_color(color);
99 window.draw(txt);
100 }
101 if !cursor_visible {
102 window.draw(&circle);
103 }
104 window.draw(&mp_text);
105 window.display();
106 }
107 Ok(())
108}