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