tauri_plugin_steam_overlay_surface/lib.rs
1//! Steam in-game overlay (Shift+Tab) support for Tauri apps.
2//!
3//! Steam's overlay works by injecting `gameoverlayrenderer64.dll` into the
4//! game process and hooking the graphics API's Present call. A Tauri app
5//! never creates a swapchain in its own process (WebView2/WebKit render
6//! out-of-process and composite via the OS), so the hook finds nothing and
7//! Shift+Tab is a no-op.
8//!
9//! This plugin gives Steam a target: a transparent, click-through window
10//! covering your main window, with a real in-process wgpu swapchain
11//! presenting empty (fully transparent) frames at vsync. Steam composites
12//! its overlay UI and notification toasts into those frames at Present time.
13//!
14//! # Usage
15//!
16//! ```rust,ignore
17//! // 1. In main(), SteamAPI_Init BEFORE building the Tauri app: the
18//! // injected DLL must be resident before the plugin creates its wgpu
19//! // device.
20//! let steam = steamworks::Client::init_app(480).ok();
21//!
22//! tauri::Builder::default()
23//! // 2. Register the plugin. It spawns the decoy surface as soon as
24//! // your main window exists.
25//! .plugin(tauri_plugin_steam_overlay_surface::init())
26//! .setup(move |app| {
27//! // 3. Forward Steam's GameOverlayActivated callback so the plugin
28//! // can hand input to the overlay and back to your game.
29//! if let Some(client) = &steam {
30//! let handle = app.handle().clone();
31//! let cb = client.register_callback(
32//! move |ev: steamworks::GameOverlayActivated| {
33//! tauri_plugin_steam_overlay_surface::on_overlay_activated(&handle, ev.active);
34//! },
35//! );
36//! std::mem::forget(cb); // keep registered for the app's lifetime
37//!
38//! // 4. Hook Steam screenshots: the decoy's backbuffer never contains
39//! // the game, so Steam's default F12 grab captures nothing.
40//! // Provide live frames instead (see capture_screenshot_png).
41//! client.screenshots().hook_screenshots(true);
42//! let handle = app.handle().clone();
43//! let shot_client = client.clone();
44//! let cb = client.register_callback(move |_: steamworks::screenshots::ScreenshotRequested| {
45//! if let Some(shot) = tauri_plugin_steam_overlay_surface::capture_screenshot_png(&handle) {
46//! let _ = shot_client.screenshots().add_screenshot_to_library(
47//! &shot.path, None, shot.width as i32, shot.height as i32);
48//! }
49//! });
50//! std::mem::forget(cb);
51//! }
52//! Ok(())
53//! })
54//! .run(tauri::generate_context!())
55//! .unwrap();
56//! ```
57//!
58//! The plugin deliberately has **no `steamworks` dependency** — your app owns
59//! Steam init and its callback pump, and forwards the one callback the plugin
60//! needs. This avoids version coupling between the plugin and your Steamworks
61//! bindings.
62//!
63//! Requires tauri's `unstable` feature (raw, webview-less windows).
64//! Windows-only today; on other platforms every call is a graceful no-op.
65
66mod screenshot;
67mod snapshot;
68mod surface;
69
70use std::sync::atomic::{AtomicBool, Ordering};
71use std::sync::Arc;
72
73use tauri::plugin::{Builder as PluginBuilder, TauriPlugin};
74use tauri::{AppHandle, Manager, Runtime};
75
76pub use screenshot::{capture_screenshot_png, CapturedScreenshot};
77pub use surface::OVERLAY_LABEL;
78
79/// Plugin configuration. Construct via [`Builder`].
80#[derive(Clone)]
81struct Config {
82 /// Label of the window the decoy surface covers.
83 main_window_label: String,
84 /// Title of the decoy window (shows up in tooling that enumerates
85 /// windows, so make it recognizable).
86 overlay_title: String,
87 /// Capture a frozen frame of the game when the overlay opens and paint it
88 /// behind Steam's UI, so Steam dims a "game frame" instead of black.
89 snapshot_backdrop: bool,
90}
91
92impl Default for Config {
93 fn default() -> Self {
94 Self {
95 main_window_label: "main".into(),
96 overlay_title: "Steam Overlay Surface".into(),
97 snapshot_backdrop: true,
98 }
99 }
100}
101
102/// Managed-state wrapper so [`on_overlay_activated`] can read the config.
103struct ConfigState(Config);
104
105/// Configures the plugin before registration.
106#[derive(Default)]
107pub struct Builder {
108 config: Config,
109}
110
111impl Builder {
112 pub fn new() -> Self {
113 Self::default()
114 }
115
116 /// Label of the window the overlay surface covers (default `"main"`).
117 pub fn main_window_label(mut self, label: impl Into<String>) -> Self {
118 self.config.main_window_label = label.into();
119 self
120 }
121
122 /// Title of the decoy window (default `"Steam Overlay Surface"`).
123 pub fn overlay_title(mut self, title: impl Into<String>) -> Self {
124 self.config.overlay_title = title.into();
125 self
126 }
127
128 /// Enable/disable the frozen-game-frame backdrop while the overlay is
129 /// open (default `true`). Disabled, Steam dims transparent black instead.
130 pub fn snapshot_backdrop(mut self, enabled: bool) -> Self {
131 self.config.snapshot_backdrop = enabled;
132 self
133 }
134
135 pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
136 let config = self.config;
137 let setup_config = config.clone();
138 let spawned = Arc::new(AtomicBool::new(false));
139 PluginBuilder::new("steam-overlay-surface")
140 .setup(move |app, _api| {
141 app.manage(ConfigState(setup_config));
142 Ok(())
143 })
144 .on_window_ready(move |window| {
145 // Fires for every window (including the decoy we create) — only the
146 // configured main window, exactly once, spawns the surface.
147 if window.label() == config.main_window_label
148 && !spawned.swap(true, Ordering::SeqCst)
149 {
150 // Deadlock guard: this hook runs inside the main window's
151 // creation path on the main thread — building the decoy
152 // window re-entrantly here wedges the whole app ("Not
153 // Responding", proven live on the Spacewar example).
154 // Defer to a background thread: window creation from
155 // non-main threads proxies through the event loop once it
156 // pumps, which is the standard supported path.
157 let config = config.clone();
158 let spawn_thread = std::thread::Builder::new()
159 .name("steam-overlay-spawn".into())
160 .spawn(move || surface::spawn(window, config));
161 if let Err(err) = spawn_thread {
162 log::warn!("steam-overlay-surface: spawn thread failed to start ({err})");
163 }
164 }
165 })
166 .build()
167 }
168}
169
170/// Initialize the plugin with default configuration.
171pub fn init<R: Runtime>() -> TauriPlugin<R> {
172 Builder::new().build()
173}
174
175/// Whether the decoy surface is up and presenting. `true` + Steam's
176/// `is_overlay_enabled()` means Shift+Tab should visibly work — useful for a
177/// settings/QA readout.
178pub fn surface_active() -> bool {
179 surface::SURFACE_ACTIVE.load(Ordering::Relaxed)
180}
181
182/// Forward Steam's `GameOverlayActivated` callback here.
183///
184/// Handles the full input handoff, each step learned from a live failure:
185/// - overlay OPEN: freeze a game frame for the backdrop (before the sheet
186/// covers it), show + focus the decoy so mouse/keyboard reach Steam's
187/// in-process hooks, and accept cursor events.
188/// - overlay CLOSED: hide the sheet immediately (after first activation
189/// Steam paints opaque frames forever — a visible decoy blacks out the
190/// game), go back to click-through, drop the backdrop, and return focus to
191/// the main window (or the webview goes deaf).
192pub fn on_overlay_activated<R: Runtime>(app: &AppHandle<R>, active: bool) {
193 surface::STEAM_OVERLAY_ACTIVE.store(active, Ordering::Relaxed);
194 log::info!(
195 "steam-overlay-surface: overlay {}",
196 if active { "opened" } else { "closed" }
197 );
198 let Some(config) = app.try_state::<ConfigState>() else {
199 log::warn!("steam-overlay-surface: plugin not registered; callback ignored");
200 return;
201 };
202 let Some(w) = app.get_window(OVERLAY_LABEL) else {
203 return;
204 };
205 let _ = w.set_ignore_cursor_events(!active);
206 if active {
207 if config.0.snapshot_backdrop {
208 if let Some(main) = app.get_window(&config.0.main_window_label) {
209 snapshot::capture_main_snapshot(&main);
210 }
211 }
212 let _ = w.show();
213 let _ = w.set_focus();
214 } else {
215 let _ = w.hide();
216 snapshot::clear_snapshot();
217 if let Some(main) = app.get_window(&config.0.main_window_label) {
218 let _ = main.set_focus();
219 }
220 }
221}