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#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
75pub use gtk_window::{
76    cairo_rounded_rect, cairo_rounded_rect_radii, gtk_begin_window_drag, gtk_close,
77    gtk_current_modifiers, gtk_focus_window, gtk_get_clipboard_text, gtk_gpu_2d_enabled,
78    gtk_gpu_surface_is_active, gtk_is_closing, gtk_is_maximized, gtk_minimize,
79    gtk_present_active_gpu_surface_now, gtk_primary_refresh_interval, gtk_reset_ime,
80    gtk_set_clipboard_text, gtk_set_cursor, gtk_set_gpu_2d_enabled, gtk_set_ime_cursor_location,
81    gtk_set_ime_surrounding_text, gtk_toggle_maximize, gtk_warp_cursor,
82    init_pango_text_measurement, launch_gtk_window, launch_gtk_window_with_config,
83    launch_gtk_window_with_scheduler, pango_font_metrics, pango_measure_styled_text,
84    pango_measure_styled_text_family, pango_measure_text, pango_measure_text_family,
85    post_platform_event, render_display_list_to_cairo, render_to_png, render_to_png_bytes,
86    resolved_font_family, set_cursor_position, try_present_display_list_gpu, warp_cursor,
87};
88#[cfg(feature = "wgpu-backend")]
89pub use wgpu_surface::{render_scene_3d_wgpu_bgra, WgpuSwapchainPresenter, WgpuWindowPresenter};
90pub use mcp_cursor::McpCursorState;
91/// Pure-Rust headless software rasterization and PNG byte export.
92///
93/// Completely decoupled from Cairo, GTK3, Pango, or X11/Wayland display servers.
94/// Operates deterministically across Linux, macOS, Windows, and CI runners.
95pub fn render_to_png_bytes_pure(
96    display_list: &strata_render::DisplayList,
97    width: i32,
98    height: i32,
99    cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
100) -> Result<Vec<u8>, String> {
101    if width <= 0 || height <= 0 {
102        return Err("Dimensions must be positive to render to PNG".to_string());
103    }
104
105    let mut fb = strata_render::FrameBuffer::new(width as usize, height as usize);
106    fb.execute_display_list(display_list);
107
108    if let Some((mcp_cursor, theme)) = cursor_overlay {
109        if mcp_cursor.fade_opacity > 0.001 {
110            let bitmap = theme.get(mcp_cursor.cursor_icon);
111            let start_x = (mcp_cursor.current_x.round() as i32) - (bitmap.xhot as i32);
112            let start_y = (mcp_cursor.current_y.round() as i32) - (bitmap.yhot as i32);
113
114            for cy in 0..bitmap.height as i32 {
115                let py = start_y + cy;
116                if py < 0 || py >= height {
117                    continue;
118                }
119                for cx in 0..bitmap.width as i32 {
120                    let px = start_x + cx;
121                    if px < 0 || px >= width {
122                        continue;
123                    }
124                    let idx = ((cy as usize) * (bitmap.width as usize) + (cx as usize)) * 4;
125                    let b = bitmap.pixels[idx] as f32 / 255.0;
126                    let g = bitmap.pixels[idx + 1] as f32 / 255.0;
127                    let r = bitmap.pixels[idx + 2] as f32 / 255.0;
128                    let a = (bitmap.pixels[idx + 3] as f32 / 255.0) * mcp_cursor.fade_opacity;
129                    if a > 0.001 {
130                        fb.set_pixel(
131                            px as usize,
132                            py as usize,
133                            strata_style::types::Color::from_f32(r, g, b, a),
134                        );
135                    }
136                }
137            }
138        }
139    }
140
141    fb.to_png_bytes()
142}
143
144#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
145pub fn render_to_png_bytes(
146    display_list: &strata_render::DisplayList,
147    width: i32,
148    height: i32,
149    cursor_overlay: Option<(&McpCursorState, &CursorTheme)>,
150) -> Result<Vec<u8>, String> {
151    render_to_png_bytes_pure(display_list, width, height, cursor_overlay)
152}
153#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
154pub fn init_pango_text_measurement() {
155    // Graceful no-op fallback when built without GTK/Pango
156}
157#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
158pub fn gtk_begin_window_drag(_x: f32, _y: f32) {}
159#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
160pub fn gtk_is_maximized() -> bool {
161    false
162}
163#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
164pub fn gtk_set_gpu_2d_enabled(_enabled: bool) {}
165#[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
166pub fn gtk_gpu_2d_enabled() -> bool {
167    false
168}
169#[cfg(target_os = "android")]
170pub use android_window::{AndroidEventLoop, AndroidWindow};
171#[cfg(target_os = "linux")]
172pub use dbus::{show_desktop_notification, DbusClient, DbusMessageDecoder, DbusMessageEncoder};
173#[cfg(target_os = "ios")]
174pub use ios_window::{IosEventLoop, IosWindow};
175#[cfg(target_os = "macos")]
176pub use macos_window::{MacOsEventLoop, MacOsWindow};
177pub use menu::{AcceleratorModifier, Menu, MenuAccelerator, MenuBar, MenuItem, MenuItemRole};
178#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
179pub use pango;
180pub use shortcuts::{ShortcutCallback, ShortcutManager, ShortcutTrigger};
181pub use single_instance::{decode_args, encode_args, SingleInstanceLock, SingleInstanceStatus};
182pub use surface::{
183    FramePacer, PresentError, PresentMode, RefreshRate, SoftwareSurfacePresenter, SurfaceConfig,
184    SurfaceHandle, SurfacePresenter, SwapchainCompositor, SwapchainFormat,
185};
186pub use tray::{
187    clear_delivered_notifications, get_delivered_notifications, DbusStatusNotifier,
188    DesktopNotification, NativeTrayHandle, TrayEvent, TrayEventChannel, TrayEventReceiver,
189    TrayEventSink, TrayIcon, TrayMenu, TrayMenuItem,
190};
191pub use vibrancy::{apply_vibrancy, clear_vibrancy, VibrancyConfig, VibrancyEffect, VibrancyError};
192#[cfg(target_os = "linux")]
193pub use wayland_window::{WaylandDecoder, WaylandEncoder, WaylandEventLoop, WaylandWindow};
194#[cfg(windows)]
195pub use win32_window::{Win32EventLoop, Win32Window};
196pub use window::{
197    CursorIcon, EventLoop, EventLoopControl, HoverTooltipStyle, LivePlatformWindow, MockEventLoop,
198    MockPlatformWindow, MonitorInfo, NativeSurfaceWindow, PlatformWindow, ThemeMode, WindowAnchor,
199    WindowConfig, WindowDecoration, WindowMode,
200};
201pub use window_manager::{WindowId, WindowManager};
202#[cfg(target_os = "linux")]
203pub use x11_window::{
204    PureX11Client, PureX11Window, X11EventLoop, X11ShmSegment, X11Window, X11WireDecoder,
205    X11WireEncoder,
206};
207
208/// Target operating system or runtime platform.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210pub enum PlatformTarget {
211    Android,
212    Ios,
213    MacOs,
214    Windows,
215    Linux,
216    WebWasm,
217    WebJs,
218}
219
220impl PlatformTarget {
221    /// Detects current runtime platform target from compile-time flags.
222    pub const fn current() -> Self {
223        #[cfg(target_os = "android")]
224        return PlatformTarget::Android;
225        #[cfg(target_os = "ios")]
226        return PlatformTarget::Ios;
227        #[cfg(target_os = "macos")]
228        return PlatformTarget::MacOs;
229        #[cfg(target_os = "windows")]
230        return PlatformTarget::Windows;
231        #[cfg(target_os = "linux")]
232        return PlatformTarget::Linux;
233        #[cfg(all(target_arch = "wasm32", not(target_os = "unknown")))]
234        return PlatformTarget::WebWasm;
235        #[cfg(not(any(
236            target_os = "android",
237            target_os = "ios",
238            target_os = "macos",
239            target_os = "windows",
240            target_os = "linux"
241        )))]
242        return PlatformTarget::WebJs;
243    }
244
245    /// Returns true if this target is a mobile operating system.
246    pub const fn is_mobile(&self) -> bool {
247        matches!(self, PlatformTarget::Android | PlatformTarget::Ios)
248    }
249
250    /// Returns true if this target is a desktop operating system.
251    pub const fn is_desktop(&self) -> bool {
252        matches!(
253            self,
254            PlatformTarget::MacOs | PlatformTarget::Windows | PlatformTarget::Linux
255        )
256    }
257
258    /// Returns true if this target runs inside a web browser.
259    pub const fn is_web(&self) -> bool {
260        matches!(self, PlatformTarget::WebWasm | PlatformTarget::WebJs)
261    }
262}
263
264/// Platform prelude module.
265pub mod prelude {
266    #[cfg(target_os = "android")]
267    pub use super::android_window::{AndroidEventLoop, AndroidWindow};
268    pub use super::csd::{ControlPlacement, CsdController, CsdGeometry, CsdHitZone};
269    pub use super::events::{KeyCode, Modifiers, MouseButton, PlatformEvent, TouchPhase};
270    #[cfg(target_os = "ios")]
271    pub use super::ios_window::{IosEventLoop, IosWindow};
272    #[cfg(target_os = "macos")]
273    pub use super::macos_window::{MacOsEventLoop, MacOsWindow};
274    pub use super::surface::{
275        FramePacer, PresentMode, RefreshRate, SurfaceConfig, SurfaceHandle, SwapchainFormat,
276    };
277    pub use super::tray::{DesktopNotification, TrayIcon, TrayMenu, TrayMenuItem};
278    #[cfg(target_os = "linux")]
279    pub use super::wayland_window::{WaylandEventLoop, WaylandWindow};
280    #[cfg(windows)]
281    pub use super::win32_window::{Win32EventLoop, Win32Window};
282    pub use super::window::{
283        CursorIcon, EventLoop, EventLoopControl, HoverTooltipStyle, LivePlatformWindow,
284        MockEventLoop, MockPlatformWindow, MonitorInfo, NativeSurfaceWindow, PlatformWindow,
285        ThemeMode, WindowAnchor, WindowConfig, WindowDecoration, WindowMode,
286    };
287    #[cfg(target_os = "linux")]
288    pub use super::x11_window::{PureX11Window, X11EventLoop, X11Window};
289    pub use super::PlatformTarget;
290}