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