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