Skip to main content

strata_platform/
lib.rs

1//! Strata Platform: Unified Native Hardware Abstraction Layer for Android, iOS, macOS, Windows, Linux, and Web.
2//!
3//! Provides zero-dependency platform windowing abstractions, client-side decorations (CSD),
4//! desktop system tray integrations, and headless mock drivers for deterministic CI testing.
5//!
6//! # Examples
7//!
8//! ```rust
9//! use strata_platform::WindowConfig;
10//!
11//! let mut config = WindowConfig::default();
12//! config.title = "My Strata App".into();
13//! assert_eq!(config.title, "My Strata App");
14//! ```
15
16#![allow(
17    clippy::too_many_arguments,
18    clippy::type_complexity,
19    clippy::field_reassign_with_default,
20    clippy::chunks_exact_to_as_chunks
21)]
22
23#[cfg(target_os = "android")]
24pub mod android_window;
25pub mod csd;
26pub mod cursor_theme;
27#[cfg(target_os = "linux")]
28pub mod dbus;
29pub mod dialog;
30pub mod events;
31#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
32pub mod gtk_window;
33#[cfg(target_os = "ios")]
34pub mod ios_window;
35#[cfg(target_os = "macos")]
36pub mod macos_window;
37pub mod mcp_cursor;
38pub mod menu;
39pub mod raw_abi;
40pub mod shortcuts;
41pub mod single_instance;
42pub mod surface;
43pub mod tray;
44pub mod vibrancy;
45#[cfg(target_os = "linux")]
46pub mod wayland_window;
47#[cfg(feature = "wgpu-backend")]
48pub mod wgpu_surface;
49#[cfg(windows)]
50pub mod win32_window;
51pub mod window;
52pub mod window_manager;
53#[cfg(target_os = "linux")]
54pub mod x11_window;
55
56#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
57pub use cairo;
58pub use csd::{ControlPlacement, CsdController, CsdGeometry, CsdHitZone};
59pub use cursor_theme::{CursorBitmap, CursorTheme};
60#[cfg(any(test, feature = "test-internals"))]
61pub use dialog::set_dialog_mock_response;
62pub use dialog::{
63    open_file, open_file_async, open_multiple_files, open_multiple_files_async, pick_folder,
64    pick_folder_async, save_file, save_file_async, show_message_box, DialogFilter,
65    DialogMockResponse, MessageBoxButtons, MessageBoxResult, MessageBoxType, OpenFileOptions,
66    PickFolderOptions, SaveFileOptions,
67};
68pub use events::{
69    decode_file_uri_to_path, parse_dropped_uri_list_to_paths, KeyCode, Modifiers, MouseButton,
70    PlatformEvent, TouchPhase,
71};
72#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
73pub use gtk;
74/// Snapshot of hardware GPU pass timings, Scene3D offscreen cache statistics, and VRAM allocation.
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
76pub struct PlatformGpuTelemetry {
77    pub gpu_timestamps_supported: bool,
78    pub gpu_shadow_pass_us: u32,
79    pub gpu_3d_pass_us: u32,
80    pub gpu_2d_overlay_pass_us: u32,
81    pub scene3d_cache_hits: u64,
82    pub scene3d_cache_misses: u64,
83    pub gpu_memory_bytes: u64,
84}
85
86/// Structured wall-clock breakdown returned by hybrid GTK + wgpu swapchain presentation so
87/// [`FrameProfileRecord`] captures real 2D raster/upload, 3D GPU encode/submit, and swapchain
88/// present durations instead of attributing everything to a single bucket.
89#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
90pub struct GpuPresentTimings {
91    /// True when the native wgpu swapchain rendered and presented the frame.
92    pub presented: bool,
93    /// Time spent rasterizing/uploading the 2D UI overlay (Cairo tiles + texture upload,
94    /// or GPU 2D batch collection when `STRATA_GPU_2D=1`).
95    pub raster_2d: std::time::Duration,
96    /// Time spent acquiring the swapchain surface, encoding 3D/2D passes, and submitting to wgpu.
97    pub wgpu_3d_submit: std::time::Duration,
98    /// Time spent in `wgpu::SurfaceTexture::present()` (swapchain handoff / vsync).
99    pub swapchain_present: std::time::Duration,
100}
101
102/// Owned surface pixel buffer captured on the UI thread so PNG compression & base64 encoding
103/// can execute on a background worker thread without stalling rendering.
104#[derive(Debug, Clone)]
105pub struct CapturedSurfaceBuffer {
106    pub width: u32,
107    pub height: u32,
108    pub stride: i32,
109    pub pixels: Vec<u8>,
110    pub is_cairo_argb32: bool,
111}
112
113impl CapturedSurfaceBuffer {
114    /// Encodes the captured pixel buffer into PNG bytes. Safe to call from any background thread.
115    pub fn encode_png_bytes(self) -> Result<Vec<u8>, String> {
116        if self.width == 0 || self.height == 0 {
117            return Err("Captured surface dimensions must be non-zero".to_string());
118        }
119        #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
120        if self.is_cairo_argb32 {
121            let surface = cairo::ImageSurface::create_for_data(
122                self.pixels,
123                cairo::Format::ARgb32,
124                self.width as i32,
125                self.height as i32,
126                self.stride,
127            )
128            .map_err(|e| format!("Failed to wrap captured surface for PNG encoding: {:?}", e))?;
129            let mut buf = Vec::new();
130            {
131                let mut cursor = std::io::Cursor::new(&mut buf);
132                surface
133                    .write_to_png(&mut cursor)
134                    .map_err(|e| format!("Failed to write PNG: {:?}", e))?;
135            }
136            return Ok(buf);
137        }
138
139        let fb = strata_render::FrameBuffer {
140            width: self.width as usize,
141            height: self.height as usize,
142            pixels: self.pixels,
143            clip_mask_stack: Vec::new(),
144        };
145        fb.to_png_bytes()
146    }
147}
148
149#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
150pub use gtk_window::{
151    cairo_rounded_rect, cairo_rounded_rect_radii, gtk_begin_window_drag, gtk_close,
152    gtk_current_modifiers, gtk_focus_window, gtk_get_clipboard_text, gtk_gpu_2d_enabled,
153    gtk_gpu_surface_is_active, gtk_is_closing, gtk_is_maximized, gtk_last_gpu_telemetry,
154    gtk_last_tile_cache_stats, gtk_minimize, gtk_present_active_gpu_surface_now,
155    gtk_present_active_gpu_surface_now_timed, gtk_primary_refresh_interval, gtk_reset_ime,
156    gtk_set_clipboard_text, gtk_set_cursor, gtk_set_gpu_2d_enabled, gtk_set_ime_cursor_location,
157    gtk_set_ime_surrounding_text, gtk_toggle_maximize, gtk_warp_cursor, init_pango_text_measurement,
158    launch_gtk_window, launch_gtk_window_with_config, launch_gtk_window_with_scheduler,
159    pango_font_metrics, pango_measure_styled_text, pango_measure_styled_text_family,
160    pango_measure_text, pango_measure_text_family, post_platform_event,
161    render_display_list_to_cairo, render_to_captured_buffer, render_to_png, render_to_png_bytes,
162    resolved_font_family, set_cursor_position, try_present_display_list_gpu,
163    try_present_display_list_gpu_timed, warp_cursor,
164};
165#[cfg(feature = "wgpu-backend")]
166pub use wgpu_surface::{render_scene_3d_wgpu_bgra, WgpuSwapchainPresenter, WgpuWindowPresenter};
167pub use mcp_cursor::McpCursorState;
168/// Pure-Rust headless software rasterization into an owned RGBA pixel buffer.
169pub fn render_to_captured_buffer_pure(
170    display_list: &strata_render::DisplayList,
171    width: i32,
172    height: i32,
173    cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
174) -> Result<CapturedSurfaceBuffer, String> {
175    if width <= 0 || height <= 0 {
176        return Err("Dimensions must be positive to render to PNG".to_string());
177    }
178
179    let mut fb = strata_render::FrameBuffer::new(width as usize, height as usize);
180    fb.execute_display_list(display_list);
181
182    if let Some((mcp_cursor, theme)) = cursor_overlay {
183        if mcp_cursor.fade_opacity > 0.001 {
184            let bitmap = theme.get(mcp_cursor.cursor_icon);
185            let start_x = (mcp_cursor.current_x.round() as i32) - (bitmap.xhot as i32);
186            let start_y = (mcp_cursor.current_y.round() as i32) - (bitmap.yhot as i32);
187
188            for cy in 0..bitmap.height as i32 {
189                let py = start_y + cy;
190                if py < 0 || py >= height {
191                    continue;
192                }
193                for cx in 0..bitmap.width as i32 {
194                    let px = start_x + cx;
195                    if px < 0 || px >= width {
196                        continue;
197                    }
198                    let idx = ((cy as usize) * (bitmap.width as usize) + (cx as usize)) * 4;
199                    let b = bitmap.pixels[idx] as f32 / 255.0;
200                    let g = bitmap.pixels[idx + 1] as f32 / 255.0;
201                    let r = bitmap.pixels[idx + 2] as f32 / 255.0;
202                    let a = (bitmap.pixels[idx + 3] as f32 / 255.0) * mcp_cursor.fade_opacity;
203                    if a > 0.001 {
204                        fb.set_pixel(
205                            px as usize,
206                            py as usize,
207                            strata_style::types::Color::from_f32(r, g, b, a),
208                        );
209                    }
210                }
211            }
212        }
213    }
214
215    Ok(CapturedSurfaceBuffer {
216        width: width as u32,
217        height: height as u32,
218        stride: width * 4,
219        pixels: fb.pixels,
220        is_cairo_argb32: false,
221    })
222}
223
224/// Pure-Rust headless software rasterization and PNG byte export.
225///
226/// Completely decoupled from Cairo, GTK3, Pango, or X11/Wayland display servers.
227/// Operates deterministically across Linux, macOS, Windows, and CI runners.
228pub fn render_to_png_bytes_pure(
229    display_list: &strata_render::DisplayList,
230    width: i32,
231    height: i32,
232    cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
233) -> Result<Vec<u8>, String> {
234    render_to_captured_buffer_pure(display_list, width, height, cursor_overlay)?.encode_png_bytes()
235}
236
237#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
238pub fn render_to_captured_buffer(
239    display_list: &strata_render::DisplayList,
240    width: i32,
241    height: i32,
242    cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
243) -> Result<CapturedSurfaceBuffer, String> {
244    render_to_captured_buffer_pure(display_list, width, height, cursor_overlay)
245}
246
247#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
248pub fn render_to_png_bytes(
249    display_list: &strata_render::DisplayList,
250    width: i32,
251    height: i32,
252    cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
253) -> Result<Vec<u8>, String> {
254    render_to_png_bytes_pure(display_list, width, height, cursor_overlay)
255}
256#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
257pub fn init_pango_text_measurement() {
258    // Graceful no-op fallback when built without GTK/Pango
259}
260#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
261pub fn gtk_begin_window_drag(_x: f32, _y: f32) {}
262#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
263pub fn gtk_is_maximized() -> bool {
264    false
265}
266#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
267pub fn gtk_set_gpu_2d_enabled(_enabled: bool) {}
268#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
269pub fn gtk_gpu_2d_enabled() -> bool {
270    false
271}
272#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
273pub fn gtk_last_tile_cache_stats() -> (u32, u32) {
274    (0, 0)
275}
276#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
277pub fn gtk_last_gpu_telemetry() -> PlatformGpuTelemetry {
278    PlatformGpuTelemetry::default()
279}
280#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
281pub fn try_present_display_list_gpu_timed(
282    _list: &strata_render::DisplayList,
283    _width: f32,
284    _height: f32,
285    _overlay_dirty: bool,
286    _transparent_bg: bool,
287    _cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
288) -> GpuPresentTimings {
289    GpuPresentTimings::default()
290}
291#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
292pub fn gtk_present_active_gpu_surface_now_timed() -> GpuPresentTimings {
293    GpuPresentTimings::default()
294}
295#[cfg(target_os = "android")]
296pub use android_window::{AndroidEventLoop, AndroidWindow};
297#[cfg(target_os = "linux")]
298pub use dbus::{show_desktop_notification, DbusClient, DbusMessageDecoder, DbusMessageEncoder};
299#[cfg(target_os = "ios")]
300pub use ios_window::{IosEventLoop, IosWindow};
301#[cfg(target_os = "macos")]
302pub use macos_window::{MacOsEventLoop, MacOsWindow};
303pub use menu::{AcceleratorModifier, Menu, MenuAccelerator, MenuBar, MenuItem, MenuItemRole};
304#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
305pub use pango;
306pub use shortcuts::{ShortcutCallback, ShortcutManager, ShortcutTrigger};
307pub use single_instance::{decode_args, encode_args, SingleInstanceLock, SingleInstanceStatus};
308pub use surface::{
309    FramePacer, PresentError, PresentMode, RefreshRate, SoftwareSurfacePresenter, SurfaceConfig,
310    SurfaceHandle, SurfacePresenter, SwapchainCompositor, SwapchainFormat,
311};
312pub use tray::{
313    clear_delivered_notifications, get_delivered_notifications, DbusStatusNotifier,
314    DesktopNotification, NativeTrayHandle, TrayEvent, TrayEventChannel, TrayEventReceiver,
315    TrayEventSink, TrayIcon, TrayMenu, TrayMenuItem,
316};
317pub use vibrancy::{apply_vibrancy, clear_vibrancy, VibrancyConfig, VibrancyEffect, VibrancyError};
318#[cfg(target_os = "linux")]
319pub use wayland_window::{WaylandDecoder, WaylandEncoder, WaylandEventLoop, WaylandWindow};
320#[cfg(windows)]
321pub use win32_window::{Win32EventLoop, Win32Window};
322pub use window::{
323    CursorIcon, EventLoop, EventLoopControl, HoverTooltipStyle, LivePlatformWindow, MockEventLoop,
324    MockPlatformWindow, MonitorInfo, NativeSurfaceWindow, PlatformWindow, ThemeMode, WindowAnchor,
325    WindowConfig, WindowDecoration, WindowMode,
326};
327pub use window_manager::{WindowId, WindowManager};
328#[cfg(target_os = "linux")]
329pub use x11_window::{
330    PureX11Client, PureX11Window, X11EventLoop, X11ShmSegment, X11Window, X11WireDecoder,
331    X11WireEncoder,
332};
333
334/// Target operating system or runtime platform.
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
336pub enum PlatformTarget {
337    Android,
338    Ios,
339    MacOs,
340    Windows,
341    Linux,
342    WebWasm,
343    WebJs,
344}
345
346impl PlatformTarget {
347    /// Detects current runtime platform target from compile-time flags.
348    pub const fn current() -> Self {
349        #[cfg(target_os = "android")]
350        return PlatformTarget::Android;
351        #[cfg(target_os = "ios")]
352        return PlatformTarget::Ios;
353        #[cfg(target_os = "macos")]
354        return PlatformTarget::MacOs;
355        #[cfg(target_os = "windows")]
356        return PlatformTarget::Windows;
357        #[cfg(target_os = "linux")]
358        return PlatformTarget::Linux;
359        #[cfg(all(target_arch = "wasm32", not(target_os = "unknown")))]
360        return PlatformTarget::WebWasm;
361        #[cfg(not(any(
362            target_os = "android",
363            target_os = "ios",
364            target_os = "macos",
365            target_os = "windows",
366            target_os = "linux"
367        )))]
368        return PlatformTarget::WebJs;
369    }
370
371    /// Returns true if this target is a mobile operating system.
372    pub const fn is_mobile(&self) -> bool {
373        matches!(self, PlatformTarget::Android | PlatformTarget::Ios)
374    }
375
376    /// Returns true if this target is a desktop operating system.
377    pub const fn is_desktop(&self) -> bool {
378        matches!(
379            self,
380            PlatformTarget::MacOs | PlatformTarget::Windows | PlatformTarget::Linux
381        )
382    }
383
384    /// Returns true if this target runs inside a web browser.
385    pub const fn is_web(&self) -> bool {
386        matches!(self, PlatformTarget::WebWasm | PlatformTarget::WebJs)
387    }
388}
389
390/// Platform prelude module.
391pub mod prelude {
392    #[cfg(target_os = "android")]
393    pub use super::android_window::{AndroidEventLoop, AndroidWindow};
394    pub use super::csd::{ControlPlacement, CsdController, CsdGeometry, CsdHitZone};
395    pub use super::events::{KeyCode, Modifiers, MouseButton, PlatformEvent, TouchPhase};
396    #[cfg(target_os = "ios")]
397    pub use super::ios_window::{IosEventLoop, IosWindow};
398    #[cfg(target_os = "macos")]
399    pub use super::macos_window::{MacOsEventLoop, MacOsWindow};
400    pub use super::surface::{
401        FramePacer, PresentMode, RefreshRate, SurfaceConfig, SurfaceHandle, SwapchainFormat,
402    };
403    pub use super::tray::{DesktopNotification, TrayIcon, TrayMenu, TrayMenuItem};
404    #[cfg(target_os = "linux")]
405    pub use super::wayland_window::{WaylandEventLoop, WaylandWindow};
406    #[cfg(windows)]
407    pub use super::win32_window::{Win32EventLoop, Win32Window};
408    pub use super::window::{
409        CursorIcon, EventLoop, EventLoopControl, HoverTooltipStyle, LivePlatformWindow,
410        MockEventLoop, MockPlatformWindow, MonitorInfo, NativeSurfaceWindow, PlatformWindow,
411        ThemeMode, WindowAnchor, WindowConfig, WindowDecoration, WindowMode,
412    };
413    #[cfg(target_os = "linux")]
414    pub use super::x11_window::{PureX11Window, X11EventLoop, X11Window};
415    pub use super::PlatformTarget;
416}