Skip to main content

oa/runtime/
window.rs

1//! SDL3 platform window used by [`super::Presenter`].
2
3use crate::{Error, Result};
4
5pub(crate) mod decoration;
6
7/// SDL3-owned Vulkan-capable window and input/event source.
8pub struct SdlWindow {
9	_sdl: sdl3::Sdl,
10	_video: sdl3::VideoSubsystem,
11	pub(crate) window: sdl3::video::Window,
12	pub(crate) client_frame: bool,
13}
14
15impl SdlWindow {
16	/// Create a resizable Vulkan-capable SDL3 window.
17	pub fn new(title: &str, width: u32, height: u32) -> Result<Self> {
18		Self::with_client_frame(title, width, height, false)
19	}
20
21	pub(crate) fn with_client_frame(
22		title: &str,
23		width: u32,
24		height: u32,
25		requested: bool,
26	) -> Result<Self> {
27		if width == 0 || height == 0 {
28			return Err(Error::invalid_argument(
29				"runtime::SdlWindow requires non-zero extent",
30			));
31		}
32		let sdl =
33			sdl3::init().map_err(|source| Error::backend_failure("SDL3", "initialization", source))?;
34		let video = sdl
35			.video()
36			.map_err(|source| Error::backend_failure("SDL3", "video initialization", source))?;
37		let create = |borderless: bool, transparent: bool| {
38			let mut builder = video.window(
39				title,
40				if requested { width.max(320) } else { width },
41				if requested { height.max(240) } else { height },
42			);
43			builder.vulkan().resizable().high_pixel_density();
44			if borderless {
45				builder.borderless();
46			}
47			if transparent {
48				let flags = builder.flags() | sdl3::video::WindowFlags::TRANSPARENT;
49				builder.set_flags(flags);
50			}
51			builder
52				.build()
53				.map_err(|source| Error::backend_failure("SDL3", "Vulkan-window creation", source))
54		};
55		let mut window = if requested {
56			create(true, true).or_else(|_| create(true, false))?
57		} else {
58			create(false, false)?
59		};
60		let mut client_frame = false;
61		if requested {
62			// SAFETY: SDL invokes this stateless callback only while this exact
63			// owned window lives. It retains no borrowed Rust state or userdata.
64			client_frame = unsafe {
65				sdl3::sys::video::SDL_SetWindowHitTest(
66					window.raw(),
67					Some(client_frame_hit_test),
68					std::ptr::null_mut(),
69				)
70			};
71			if client_frame {
72				window
73					.set_minimum_size(320, 240)
74					.map_err(|source| Error::backend_failure("SDL3", "viewer minimum extent", source))?;
75			} else {
76				window = create(false, false)?;
77			}
78		}
79		Ok(Self {
80			_sdl: sdl,
81			_video: video,
82			window,
83			client_frame,
84		})
85	}
86
87	/// Native requests mutate SDL's window, not the retained Rust owner. The
88	/// shared surface borrow still prevents destruction while a Presenter exists.
89	pub(crate) fn minimize(&self) -> Result<()> {
90		// SAFETY: live owned SDL window on the event thread.
91		if unsafe { sdl3::sys::video::SDL_MinimizeWindow(self.window.raw()) } {
92			Ok(())
93		} else {
94			Err(Error::backend_failure(
95				"SDL3",
96				"window minimize",
97				sdl3::get_error(),
98			))
99		}
100	}
101
102	pub(crate) fn toggle_maximized(&self) -> Result<()> {
103		// SAFETY: live owned SDL window on the event thread; no Rust field is mutated.
104		let success = unsafe {
105			if self.window.is_maximized() {
106				sdl3::sys::video::SDL_RestoreWindow(self.window.raw())
107			} else {
108				sdl3::sys::video::SDL_MaximizeWindow(self.window.raw())
109			}
110		};
111		if success {
112			Ok(())
113		} else {
114			Err(Error::backend_failure(
115				"SDL3",
116				"window maximize/restore",
117				sdl3::get_error(),
118			))
119		}
120	}
121
122	pub(crate) fn toggle_fullscreen(&self) -> Result<()> {
123		let fullscreen = self.window.fullscreen_state() != sdl3::video::FullscreenType::Off;
124		// SAFETY: live owned SDL window on the event thread; compositor owns the transition.
125		if unsafe { sdl3::sys::video::SDL_SetWindowFullscreen(self.window.raw(), !fullscreen) } {
126			Ok(())
127		} else {
128			Err(Error::backend_failure(
129				"SDL3",
130				"window fullscreen",
131				sdl3::get_error(),
132			))
133		}
134	}
135
136	/// Return the Vulkan instance extensions SDL requires for this window.
137	pub fn required_instance_extensions(&self) -> Result<Vec<String>> {
138		self
139			.window
140			.vulkan_instance_extensions()
141			.map_err(|source| Error::backend_failure("SDL3", "Vulkan instance-extension query", source))
142	}
143
144	/// Return the drawable pixel extent used by Vulkan presentation.
145	///
146	/// This deliberately differs from SDL's logical window size on high-density
147	/// displays. A zero extent means the window is minimized and must not cause
148	/// swapchain allocation or acquisition.
149	pub fn drawable_extent(&self) -> [u32; 2] {
150		let (width, height) = self.window.size_in_pixels();
151		[width, height]
152	}
153
154	/// Obtain SDL's process-wide event pump for Presenter/UI input.
155	pub fn event_pump(&self) -> Result<sdl3::EventPump> {
156		self
157			._sdl
158			.event_pump()
159			.map_err(|source| Error::backend_failure("SDL3", "event-pump creation", source))
160	}
161
162	/// Enable or disable platform text input (`SDL_StartTextInput` /
163	/// `SDL_StopTextInput`).  Keep it enabled only while a text widget holds
164	/// focus so the OS does not steal key events or show stray IME UI.
165	pub fn set_text_input_active(&self, active: bool) {
166		let util = self._video.text_input();
167		if active {
168			util.start(&self.window);
169		} else {
170			util.stop(&self.window);
171		}
172	}
173
174	/// Anchor the OS IME candidate window at a physical-pixel rect.
175	///
176	/// `cursor_offset` is the caret's pixel offset from the rect's left edge.
177	/// SDL expects window-logical coordinates, so the rect is divided by the
178	/// window's pixel scale before the call.
179	pub fn set_text_input_area(&self, x: i32, y: i32, w: u32, h: u32, cursor_offset: i32) {
180		let (sx, sy) = crate::input::sdl_events::window_pixel_scale(&self.window);
181		let logical = sdl3::rect::Rect::new(
182			(x as f32 / sx) as i32,
183			(y as f32 / sy) as i32,
184			(w as f32 / sx) as u32,
185			(h as f32 / sy) as u32,
186		);
187		self
188			._video
189			.text_input()
190			.set_rect(&self.window, logical, (cursor_offset as f32 / sx) as i32);
191	}
192
193	/// Ids of standard-layout gamepads already connected — open each with
194	/// [`SdlWindow::open_gamepad`] since already-present pads don't re-emit
195	/// `GamepadAdded`.
196	pub fn connected_gamepads(&self) -> Vec<u32> {
197		self
198			._sdl
199			.gamepad()
200			.and_then(|subsystem| subsystem.gamepads())
201			.map(|ids| ids.iter().map(|id| id.raw()).collect())
202			.unwrap_or_default()
203	}
204
205	/// Open a connected standard-layout gamepad.
206	///
207	/// Call with the instance id from a `GamepadAdded` event and keep the
208	/// returned handle alive for as long as the pad stays connected — dropping
209	/// it closes the device. Button/axis state arrives through the event pump
210	/// as `Gamepad*` events.
211	pub fn open_gamepad(&self, id: u32) -> Result<sdl3::gamepad::Gamepad> {
212		let subsystem = self
213			._sdl
214			.gamepad()
215			.map_err(|source| Error::backend_failure("SDL3", "gamepad subsystem", source))?;
216		subsystem
217			.open(sdl3::joystick::JoystickId::new(id))
218			.map_err(|source| Error::backend_failure("SDL3", "gamepad open", source))
219	}
220}
221
222// SDL supplies the current native dimensions/flags during interactive resizing,
223// so no copied geometry, RefCell borrow, or captured pointer needs refreshing.
224unsafe extern "C" fn client_frame_hit_test(
225	window: *mut sdl3::sys::video::SDL_Window,
226	point: *const sdl3::sys::rect::SDL_Point,
227	_: *mut std::ffi::c_void,
228) -> sdl3::sys::video::SDL_HitTestResult {
229	use sdl3::sys::video::*;
230	if window.is_null() || point.is_null() {
231		return SDL_HITTEST_NORMAL;
232	}
233	let mut width = 0;
234	let mut height = 0;
235	// SAFETY: SDL owns the callback invocation and supplies live window/point pointers.
236	unsafe {
237		if !SDL_GetWindowSize(window, &mut width, &mut height) {
238			return SDL_HITTEST_NORMAL;
239		}
240		let flags = SDL_GetWindowFlags(window);
241		decoration::hit_test(
242			(*point).x,
243			(*point).y,
244			width,
245			height,
246			flags.0 & SDL_WINDOW_RESIZABLE.0 != 0,
247			flags.0 & SDL_WINDOW_MAXIMIZED.0 != 0,
248		)
249		.to_ll()
250	}
251}