window_test/
window-test.rs1use sfml::{
2 graphics::{Color, Font, RenderTarget, RenderWindow, Text, Transformable},
3 window::{ContextSettings, Event, Key, Style, VideoMode},
4 SfResult,
5};
6
7struct WindowConfig {
8 mode: (u32, u32),
9 title: &'static str,
10 style: Style,
11}
12
13fn main() -> SfResult<()> {
14 let configs = [
15 WindowConfig {
16 mode: (320, 240),
17 title: "(Windowed) Retro",
18 style: Style::CLOSE,
19 },
20 WindowConfig {
21 mode: (640, 480),
22 title: "(Windowed) Classic",
23 style: Style::DEFAULT,
24 },
25 WindowConfig {
26 mode: (800, 600),
27 title: "(Windowed) Big",
28 style: Style::TITLEBAR,
29 },
30 ];
31 let mut cfg_idx = 2usize;
32 let mut rw = RenderWindow::new(
33 configs[cfg_idx].mode,
34 "Window test",
35 Style::CLOSE,
36 &ContextSettings::default(),
37 )?;
38 let font = Font::from_memory_static(include_bytes!("resources/sansation.ttf"))?;
39 let fs_modes = VideoMode::fullscreen_modes();
40
41 while rw.is_open() {
42 while let Some(ev) = rw.poll_event() {
43 match ev {
44 Event::Closed => rw.close(),
45 Event::KeyPressed { code, .. } => match code {
46 Key::Up => cfg_idx = cfg_idx.saturating_sub(1),
47 Key::Down => {
48 if cfg_idx + 1 < configs.len() + fs_modes.len() {
49 cfg_idx += 1
50 }
51 }
52 Key::Enter => match configs.get(cfg_idx) {
53 Some(cfg) => {
54 rw.recreate(cfg.mode, cfg.title, cfg.style, &ContextSettings::default())
55 }
56 None => match fs_modes.get(cfg_idx - configs.len()) {
57 Some(mode) => rw.recreate(
58 *mode,
59 "Fullscreen",
60 Style::FULLSCREEN,
61 &ContextSettings::default(),
62 ),
63 None => {
64 eprintln!("Invalid index: {cfg_idx}");
65 }
66 },
67 },
68 _ => {}
69 },
70 _ => {}
71 }
72 }
73 rw.clear(Color::BLACK);
74 let fontsize = 16;
75 let mut txt = Text::new("Arrow keys to select mode, enter to set.", &font, fontsize);
76 rw.draw(&txt);
77 let mut y = fontsize as f32;
78 for (i, cfg) in configs.iter().enumerate() {
79 let fc = if i == cfg_idx {
80 Color::YELLOW
81 } else {
82 Color::WHITE
83 };
84 txt.set_fill_color(fc);
85 txt.set_string(&format!(
86 "{}x{} \"{}\" ({:?})",
87 cfg.mode.0, cfg.mode.1, cfg.title, cfg.style
88 ));
89 txt.set_position((0., y));
90 rw.draw(&txt);
91 y += fontsize as f32;
92 }
93 let mut i = configs.len();
94 y += fontsize as f32;
95 txt.set_position((0., y));
96 txt.set_fill_color(Color::WHITE);
97 txt.set_string("= Fullscreen modes =");
98 rw.draw(&txt);
99 for mode in fs_modes.iter() {
100 let n_rows = 23;
101 let column = i / n_rows;
102 let row = i % n_rows;
103 let fc = if i == cfg_idx {
104 Color::YELLOW
105 } else {
106 Color::WHITE
107 };
108 txt.set_fill_color(fc);
109 let left_pad = 16.0;
110 let x = left_pad + (column * 128) as f32;
111 let gap = 16.0;
112 let y = y + gap + (row * fontsize as usize) as f32;
113 txt.set_position((x, y));
114 txt.set_string(&format!(
115 "{}x{}x{}",
116 mode.width, mode.height, mode.bits_per_pixel
117 ));
118 rw.draw(&txt);
119 i += 1;
120 }
121 rw.display();
122 }
123 Ok(())
124}