Skip to main content

sui/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Public Rust facade for SUI.
4//!
5//! Most applications can import [`prelude`] and construct an [`App`] with one
6//! or more [`Window`] values. Lower-level runtime, scene, renderer, and widget
7//! types are re-exported for custom widgets, embedding, tests, and tooling.
8//!
9//! ```no_run
10//! use sui::prelude::*;
11//!
12//! fn main() -> Result<()> {
13//!     App::new()
14//!         .main_window("Hello SUI", Label::new("Ready"))
15//!         .run()
16//! }
17//! ```
18
19use std::{
20    any::{Any, TypeId},
21    collections::HashMap,
22    fmt,
23    sync::Arc,
24};
25
26/// User-facing application, window, resource, and wake-handle builders.
27pub mod app;
28/// Composite widgets and application-shell building blocks.
29pub mod composites;
30/// Layout and containment widgets.
31pub mod containers;
32/// Primitive controls, labels, inputs, and icons.
33pub mod controls;
34
35#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
36pub use app::UiHandle;
37pub use app::{App, ResourceRegistry, Window};
38
39pub use composites::{
40    ActionTilePaint, BrowserTabBar, BusyIndicator, CalloutPaint, CodePanelPaint, CodeTextLine,
41    CodeTextPaint, CodeTextSpan, CommandButtonFill, CommandButtonPaint, CommandGroup, ContextMenu,
42    Dialog, DisclosureButtonPaint, DockPanel, Drawer, EmptyState, EmptyStatePaint, FieldGroup,
43    FormRow, FormSection, FramedField, HairlineEdge, Menu, MenuItem, Modal, PanelSection, Popover,
44    PopoverAlignment, PresetStrip, ProgressBar, PropertyRow, PropertyRowLayout, SectionLabel,
45    SectionLabelPaint, SectionPanelGeometry, SectionPanelPaint, SideSheet, SideSheetPlacement,
46    Spinner, StatusBar, StatusBarHost, StatusBarSegment, Surface, SurfaceAppearance, SurfaceBorder,
47    SurfaceElevation, SurfaceRole, TabBar, Tabs, ToolPalette, ToolPaletteItem, Toolbar, Tooltip,
48    TooltipAlignment, TooltipPlacement, paint_action_tile, paint_border, paint_callout,
49    paint_code_lines, paint_code_panel, paint_command_button, paint_disclosure_button,
50    paint_empty_state, paint_hairline, paint_placement_badge_with, paint_rounded_panel,
51    paint_rounded_rect, paint_section_label, paint_section_label_detail, paint_section_panel,
52};
53pub use containers::{
54    Align, Background, Dock, FixedPaneSplit, Flex, MeasuredBottomDock, Overflow, RebuildOnChange,
55    RebuildOnConstraints, ScrollAxes, ScrollBar, ScrollState, ScrollView, SemanticRegion, SizedBox,
56    Stack, SwitchView, TrailingSlotRow, VirtualScrollView,
57};
58pub use controls::{
59    BUILTIN_ICON_GLYPHS, Button, ButtonAppearance, Checkbox, CheckboxIndicatorState,
60    ChoiceAppearance, ComboBox, DateTimeInput, Divider, FieldAppearance, Icon, IconButton,
61    IconButtonPaint, IconGlyph, Label, Link, MultilineTextInput, NumberInput, PasswordInput,
62    RadioButton, RadioGroup, Select, Separator, Slider, SpinBox, Switch, TextArea, TextInput,
63    draw_glyph, paint_checkbox_indicator, paint_icon_button, register_builtin_icon_resources,
64};
65pub use sui_core::{
66    AsyncWakeToken, Clipboard, ClipboardBackend, Color, ColorSpace, CustomEvent, DirtyRegion,
67    DpiInfo, DragDropScope, DragEvent, DragEventKind, DragOutcome, DragPayload, DragPreview,
68    DragScopeId, DragSessionId, DropEffect, Error, Event, FontHandle, ImageHandle, ImeEvent,
69    InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState, KeyboardEvent,
70    LocalClipboardBackend, Modifiers, Path, PathBuilder, PathElement, Point, PointerButton,
71    PointerButtons, PointerEvent, PointerEventKind, PointerKind, Rect, Result, ScrollDelta,
72    SemanticsAction, SemanticsActionRequest, SemanticsEvent, SemanticsNode, SemanticsRole,
73    SemanticsState, SemanticsTextRange, SemanticsValue, Size, SurfaceId, TimerToken, ToggleState,
74    Transform, Vector, WakeEvent, WidgetId, WindowEvent, WindowId,
75};
76pub use sui_layout::Padding as Insets;
77pub use sui_layout::{
78    Alignment, Axis, Constraints, FlexAlignContent, FlexBasis, FlexItem, FlexItemLayout,
79    FlexJustify, FlexLayout, FlexLineLayout, FlexStyle, FlexWrap, LayoutContext, Padding,
80    arrange_flex, flex_layout,
81};
82#[cfg(all(target_os = "android", feature = "mobile"))]
83pub use sui_platform::AndroidApp;
84#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
85pub use sui_platform::{
86    AccessibilitySnapshot, DesktopAutomationAction, DesktopAutomationConfig, DesktopPlatform,
87    HeadlessPlatform, PlatformWindow, Waker, WindowOutputDiagnostics, window_output_diagnostics,
88};
89#[cfg(feature = "wgpu")]
90pub use sui_render_wgpu::{
91    RendererCapabilities, RendererInterop, StemDarkening, TextCoveragePolicy, TextHinting,
92    WgpuExternalTextureContext, WgpuExternalTextureRegistry, WgpuRenderer,
93};
94pub use sui_runtime::{
95    Application as RuntimeApplication, ArrangeCtx, CacheMetrics, CacheMetricsDelta,
96    DEFAULT_SUI_LOGO_SVG, EXTERNAL_WAKE_KIND, EmbeddedSvgImageResource, EventCtx, EventPhase,
97    FocusState, FramePhase, FramePhaseSample, FrameSchedule, MeasureCtx, PaintCtx,
98    PresentationLatencyDiagnostics, RenderDiagnostics, RenderOutput, RendererSubmissionDiagnostics,
99    RetainedPacketRebuildDiagnostics, Runtime, SceneStatistics, SceneStatisticsDetailMode,
100    SemanticsCtx, SingleChild, StackHostOptions, StackOrderPolicy, StackSurfaceOptions,
101    TextCacheDeltaDiagnostics, TextCacheDiagnostics, Widget, WidgetChildren,
102    WidgetGeometrySnapshot, WidgetGraphSnapshot, WidgetNodeSnapshot, WidgetPod,
103    WidgetPodMutVisitor, WidgetPodVisitor, WindowBuilder, WindowColorManagementMode,
104    WindowDynamicRangeMode, WindowIcon, WindowOutputColorPrimaries, WindowPerformanceSnapshot,
105    WindowPerformanceSummary, WindowRenderOptions, WindowStemDarkening, WindowTextCoveragePolicy,
106    WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode, clear_window_render_options,
107    default_sui_logo_image, set_window_render_options, set_window_scene_statistics_detail_mode,
108    window_performance_snapshot, window_performance_summary, window_render_options,
109    window_scene_statistics_detail_mode,
110};
111pub use sui_scene::{
112    Border, Brush, GradientStop, ImageRegistry, ImageSource, RegisteredExternalImage,
113    RegisteredImage, RegisteredImageFormat, Scene, SceneCommand, SceneFrame, ShadowParams,
114    StrokeStyle, TextRenderCoveragePolicy, TextRenderHinting, TextRenderMode, TextRenderPolicy,
115    TextRenderStemDarkening, TextSubpixelOrder, WidgetShader,
116};
117pub use sui_text::{
118    FontFamilyStack, FontFeature, FontFeatures, FontRegistry, FontStretch, FontStyle, FontWeight,
119    PersistentTextLayout, RegisteredFont, ResolvedTextFace, ShapedGlyph, ShapedText,
120    ShapedTextWindow, TextAffinity, TextAlign, TextCluster, TextCursor, TextDirection,
121    TextDocument, TextFlowDirection, TextGlyphInstance, TextLayout, TextLayoutHandle, TextLayoutId,
122    TextLayoutMetadata, TextLayoutRegistry, TextLayoutRequest, TextLayoutRun, TextLayoutVersion,
123    TextLayoutView, TextLine, TextLineWindow, TextMeasurement, TextParagraph, TextParagraphLayout,
124    TextParagraphStyle, TextRun, TextRunView, TextSelection, TextSelectionGeometry, TextSpan,
125    TextSpanId, TextStyle, TextWrap, TextWritingMode,
126};
127pub use sui_widgets::SignalMeter;
128pub use sui_widgets::animation::{
129    ANIMATION_DOCUMENT_VERSION, AnimatedValue, AnimationBinding, AnimationBindingInvalidation,
130    AnimationDocument, AnimationDocumentFormatError, AnimationEditorCommand, AnimationEditorState,
131    AnimationPlayer, AnimationProperty, AnimationPropertyPath, AnimationSelection,
132    AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind, Blink, Clip,
133    CompiledClip, CompiledTimeline, CompiledTrack, Easing, Interpolate, Keyframe,
134    KeyframeSelection, LoopMode, PlaybackState, Pulse, SampleBatch, SampleBuffer,
135    SampledAnimationValue, SharedCompiledTimeline, SpringF32, Timeline, TimelineBindingSink,
136    TimelinePlayer, TimelineSnap, TimelineTick, Track, Transition,
137    invalidation_for_animation_property,
138};
139pub use sui_widgets::{
140    ActionCard, Breadcrumb, BreadcrumbItem, BrushPreview, BrushPreviewShape, BrushPreviewSpec,
141    Canvas, CanvasRuler, CanvasRulerAxis, CanvasShape, CanvasStroke, CanvasViewport, ColorPalette,
142    ColorPaletteSwatch, ColorPicker, ColorSwatch, ControlMetrics, ControlPalette, ControlSize,
143    ControlTypography, CoverageDots, CoverageDotsConfig, DataGrid, DefaultTheme, DetailRow,
144    DragDropHost, Draggable, DropTarget, EffectToken, FloatingStack, FloatingViewConfig,
145    FloatingViewSnapshot, FloatingWorkspace, FloatingWorkspaceState, HdrColorRoles,
146    HdrEffectTokens, HdrLuminanceTokens, HdrMaterialTokens, HdrPolicyTokens, HdrThemeMode,
147    HdrThemeTokens, Image, ImageFit, LayerList, LayerListItem, LayerListReorderChange,
148    LeadingLabelCellPaint, ListItem, ListView, MaterialToken, PathBar, PixelCanvas,
149    PixelCanvasBlendMode, PixelCanvasBrushShape, PixelCanvasExportSnapshot, PixelCanvasState,
150    PixelCanvasTool, PlacementBadge, PlacementBadgePaint, ReorderableList, ReorderableListChange,
151    ResizablePane, ResolvedEffectStyle, ResolvedHdrStyle, ResolvedMaterialStyle, RichText,
152    RichTextSourceMap, RichTextSourceSpan, SegmentedControl, SegmentedControlItem, SelectionChange,
153    SelectionEntry, SelectionIntent, SelectionOrder, SelectionOwnerId, SelectionPayload,
154    SelectionPoint, SelectionScope, SemanticColorToken, SemanticTone, SplitView, StatusBadge,
155    SurfacePalette, TEXT_COMMAND_EVENT_KIND, Table, TableColumn, TableColumnAlignment, TableRow,
156    TextBlockPaint, TextCellPaint, TextCommand, TextSelectionInfo, TextSurface,
157    TextSurfaceOverlayKind, TextSurfaceStyleOverlay, TextSurfaceStyleSpan, ThemeAspectRatios,
158    ThemeBlurScale, ThemeBreakpoints, ThemeColorScheme, ThemeColors, ThemeContainers, ThemeDensity,
159    ThemeFontFamilies, ThemeFontStack, ThemeFontWeights, ThemeLeading, ThemeMotion,
160    ThemePerspective, ThemeRadii, ThemeShadow, ThemeShadowLayer, ThemeShadows, ThemeTextScale,
161    ThemeTextToken, ThemeTracking, TreeItem, TreeView, VirtualTable, VirtualTableColumn,
162    VirtualTableRowActivationKind, VirtualTableRowContext, VirtualTableSortDirection,
163    WidgetColorRole, WidgetEffectRole, WidgetLuminanceRole, WidgetMaterialRole,
164    detail_row_height_for_value, paint_aligned_text, paint_coverage_dots,
165    paint_coverage_dots_with_config, paint_detail_row_at, paint_leading_label_cell,
166    paint_placement_badge, paint_progress_bar, paint_single_line_aligned_text, paint_status_badge,
167    paint_text_block, paint_text_cell, paint_theme_shadow, resolve_effect_role,
168    resolve_luminance_role, resolve_material_role, resolve_semantic_color,
169    resolve_widget_hdr_style, wrap_text_lines,
170};
171
172/// Marker trait for type-indexed application theme extensions.
173pub trait ThemeExtension: Any + Send + Sync {}
174
175impl<T> ThemeExtension for T where T: Any + Send + Sync {}
176
177/// Type-indexed storage for application-specific theme values.
178#[derive(Clone, Default)]
179pub struct ThemeExtensions {
180    values: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
181}
182
183impl ThemeExtensions {
184    /// Create empty extension storage.
185    pub fn new() -> Self {
186        Self::default()
187    }
188
189    /// Insert or replace an extension, returning the previous value when present.
190    pub fn insert<T>(&mut self, value: T) -> Option<Arc<T>>
191    where
192        T: ThemeExtension,
193    {
194        self.values
195            .insert(TypeId::of::<T>(), Arc::new(value))
196            .and_then(|previous| Arc::downcast::<T>(previous).ok())
197    }
198
199    /// Borrow an extension by its concrete type.
200    pub fn get<T>(&self) -> Option<&T>
201    where
202        T: ThemeExtension,
203    {
204        self.values
205            .get(&TypeId::of::<T>())
206            .and_then(|value| value.as_ref().downcast_ref::<T>())
207    }
208
209    /// Clone the shared pointer for an extension by its concrete type.
210    pub fn get_arc<T>(&self) -> Option<Arc<T>>
211    where
212        T: ThemeExtension,
213    {
214        self.values
215            .get(&TypeId::of::<T>())
216            .and_then(|value| Arc::clone(value).downcast::<T>().ok())
217    }
218
219    /// Return whether an extension of type `T` is registered.
220    pub fn contains<T>(&self) -> bool
221    where
222        T: ThemeExtension,
223    {
224        self.values.contains_key(&TypeId::of::<T>())
225    }
226
227    /// Remove and return an extension by its concrete type.
228    pub fn remove<T>(&mut self) -> Option<Arc<T>>
229    where
230        T: ThemeExtension,
231    {
232        self.values
233            .remove(&TypeId::of::<T>())
234            .and_then(|value| Arc::downcast::<T>(value).ok())
235    }
236
237    /// Return whether no extensions are registered.
238    pub fn is_empty(&self) -> bool {
239        self.values.is_empty()
240    }
241
242    /// Return the number of registered extension types.
243    pub fn len(&self) -> usize {
244        self.values.len()
245    }
246}
247
248impl fmt::Debug for ThemeExtensions {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("ThemeExtensions")
251            .field("len", &self.values.len())
252            .finish()
253    }
254}
255
256/// Application-level colors, built-in widget theme, and custom extensions.
257#[derive(Debug, Clone)]
258pub struct Theme {
259    /// Default application background color.
260    pub background: Color,
261    /// Default application foreground color.
262    pub foreground: Color,
263    /// Theme used by SUI's built-in widgets.
264    pub default_widgets: DefaultTheme,
265    /// Type-indexed application theme extensions.
266    pub extensions: ThemeExtensions,
267}
268
269impl Default for Theme {
270    fn default() -> Self {
271        let default_widgets = DefaultTheme::default();
272        Self {
273            background: default_widgets.palette.surface,
274            foreground: default_widgets.palette.text,
275            default_widgets,
276            extensions: ThemeExtensions::default(),
277        }
278    }
279}
280
281impl Theme {
282    /// Create the default application theme.
283    pub fn new() -> Self {
284        Self::default()
285    }
286
287    /// Replace the theme used by built-in widgets.
288    pub fn with_default_widgets(mut self, theme: DefaultTheme) -> Self {
289        self.default_widgets = theme;
290        self
291    }
292
293    /// Add a typed extension using builder syntax.
294    pub fn with_extension<T>(mut self, value: T) -> Self
295    where
296        T: ThemeExtension,
297    {
298        self.extensions.insert(value);
299        self
300    }
301
302    /// Insert or replace a typed theme extension.
303    pub fn insert_extension<T>(&mut self, value: T) -> Option<Arc<T>>
304    where
305        T: ThemeExtension,
306    {
307        self.extensions.insert(value)
308    }
309
310    /// Borrow a typed theme extension.
311    pub fn extension<T>(&self) -> Option<&T>
312    where
313        T: ThemeExtension,
314    {
315        self.extensions.get::<T>()
316    }
317
318    /// Clone the shared pointer for a typed theme extension.
319    pub fn extension_arc<T>(&self) -> Option<Arc<T>>
320    where
321        T: ThemeExtension,
322    {
323        self.extensions.get_arc::<T>()
324    }
325
326    /// Return whether a typed theme extension is present.
327    pub fn has_extension<T>(&self) -> bool
328    where
329        T: ThemeExtension,
330    {
331        self.extensions.contains::<T>()
332    }
333
334    /// Remove and return a typed theme extension.
335    pub fn remove_extension<T>(&mut self) -> Option<Arc<T>>
336    where
337        T: ThemeExtension,
338    {
339        self.extensions.remove::<T>()
340    }
341}
342
343/// Lower-level application builder for runtime and platform integration.
344///
345/// Regular applications should prefer [`App`]. This type remains public for
346/// custom embedding, debug tooling, and direct [`Runtime`] construction.
347pub struct Application {
348    inner: RuntimeApplication,
349    #[cfg(feature = "wgpu")]
350    feathering_enabled: bool,
351    #[cfg(feature = "wgpu")]
352    feather_width: f32,
353    #[cfg(feature = "wgpu")]
354    external_texture_registry: Option<WgpuExternalTextureRegistry>,
355    initial_window_render_options: Option<WindowRenderOptions>,
356}
357
358impl Default for Application {
359    fn default() -> Self {
360        let mut inner = RuntimeApplication::default();
361        sui_widgets::register_builtin_icon_resources(&mut inner)
362            .expect("built-in Lucide icon resources should be valid");
363        Self {
364            inner,
365            #[cfg(feature = "wgpu")]
366            feathering_enabled: WgpuRenderer::new().feathering_enabled(),
367            #[cfg(feature = "wgpu")]
368            feather_width: WgpuRenderer::new().feather_width(),
369            #[cfg(feature = "wgpu")]
370            external_texture_registry: None,
371            initial_window_render_options: None,
372        }
373    }
374}
375
376impl Application {
377    /// Create an empty application with built-in icon resources registered.
378    pub fn new() -> Self {
379        Self::default()
380    }
381
382    /// Add a lower-level window builder.
383    pub fn window(mut self, window: WindowBuilder) -> Self {
384        self.inner = self.inner.window(window);
385        self
386    }
387
388    #[cfg(feature = "wgpu")]
389    /// Enable or disable analytic-edge feathering in the WGPU renderer.
390    pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
391        self.feathering_enabled = enabled;
392        self
393    }
394
395    #[cfg(feature = "wgpu")]
396    /// Set the analytic-edge feather width in logical pixels.
397    pub fn with_feather_width(mut self, feather_width: f32) -> Self {
398        self.feather_width = feather_width.max(0.0);
399        self
400    }
401
402    #[cfg(feature = "wgpu")]
403    /// Attach an app-owned external texture registry.
404    pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
405        self.external_texture_registry = Some(registry);
406        self
407    }
408
409    #[cfg(feature = "wgpu")]
410    /// Return whether renderer feathering is enabled.
411    pub fn feathering_enabled(&self) -> bool {
412        self.feathering_enabled
413    }
414
415    #[cfg(feature = "wgpu")]
416    /// Return the configured renderer feather width.
417    pub fn feather_width(&self) -> f32 {
418        self.feather_width
419    }
420
421    #[cfg(feature = "wgpu")]
422    /// Borrow the configured external texture registry, if present.
423    pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
424        self.external_texture_registry.as_ref()
425    }
426
427    /// Set initial render options applied to every window at startup.
428    pub fn with_window_render_options(mut self, options: WindowRenderOptions) -> Self {
429        self.initial_window_render_options = Some(options.clamped());
430        self
431    }
432
433    /// Return the initial render options, if configured.
434    pub fn initial_window_render_options(&self) -> Option<WindowRenderOptions> {
435        self.initial_window_render_options
436    }
437
438    /// Register a font with an explicit handle.
439    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
440        self.inner.register_font(handle, font)
441    }
442
443    /// Register font bytes and allocate a handle.
444    pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
445        self.inner.register_font_bytes(data)
446    }
447
448    /// Register an image with an explicit handle.
449    pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
450        self.inner.register_image(handle, image)
451    }
452
453    /// Register RGBA8 pixels and allocate an image handle.
454    pub fn register_rgba_image(
455        &mut self,
456        width: u32,
457        height: u32,
458        data: impl Into<Vec<u8>>,
459    ) -> Result<ImageHandle> {
460        self.inner.register_rgba_image(width, height, data)
461    }
462
463    /// Register SVG bytes at their intrinsic size and allocate an image handle.
464    pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
465        self.inner.register_svg_image(data)
466    }
467
468    /// Register SVG bytes at their intrinsic size with an explicit handle.
469    pub fn register_svg_image_with_handle(
470        &mut self,
471        handle: ImageHandle,
472        data: impl AsRef<[u8]>,
473    ) -> Result<()> {
474        self.inner.register_svg_image_with_handle(handle, data)
475    }
476
477    /// Rasterize SVG bytes at an explicit size and allocate an image handle.
478    pub fn register_svg_image_at_size(
479        &mut self,
480        width: u32,
481        height: u32,
482        data: impl AsRef<[u8]>,
483    ) -> Result<ImageHandle> {
484        self.inner.register_svg_image_at_size(width, height, data)
485    }
486
487    /// Rasterize SVG bytes at an explicit size and handle.
488    pub fn register_svg_image_at_size_with_handle(
489        &mut self,
490        handle: ImageHandle,
491        width: u32,
492        height: u32,
493        data: impl AsRef<[u8]>,
494    ) -> Result<()> {
495        self.inner
496            .register_svg_image_at_size_with_handle(handle, width, height, data)
497    }
498
499    /// Register one embedded SVG resource.
500    pub fn register_embedded_svg_image(
501        &mut self,
502        resource: EmbeddedSvgImageResource,
503    ) -> Result<()> {
504        self.inner.register_embedded_svg_image(resource)
505    }
506
507    /// Register multiple embedded SVG resources.
508    pub fn register_embedded_svg_images(
509        &mut self,
510        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
511    ) -> Result<()> {
512        self.inner.register_embedded_svg_images(resources)
513    }
514
515    /// Build the retained runtime without starting a platform event loop.
516    pub fn build(self) -> Result<Runtime> {
517        self.inner.build()
518    }
519
520    #[cfg(any(feature = "desktop", feature = "web"))]
521    /// Build and run the application on the default desktop or web platform.
522    pub fn run(self) -> Result<()> {
523        let feathering_enabled = self.feathering_enabled;
524        let feather_width = self.feather_width;
525        let external_texture_registry = self.external_texture_registry.clone();
526        let initial_window_render_options = self.initial_window_render_options;
527        let runtime = self.build()?;
528        let mut platform = DesktopPlatform::new()
529            .with_feathering_enabled(feathering_enabled)
530            .with_feather_width(feather_width);
531        if let Some(registry) = external_texture_registry {
532            platform.set_external_texture_registry(registry);
533        }
534        if let Some(options) = initial_window_render_options {
535            for window_id in runtime.window_ids() {
536                set_window_render_options(window_id, options);
537            }
538        }
539        let _ = platform.run(runtime)?;
540        Ok(())
541    }
542
543    /// Like [`run`](Self::run) but invokes `on_ready` with a [`Waker`] once the event loop is
544    /// created (before it starts running), so the caller can wake the UI from a background
545    /// thread — e.g. run startup work off the UI thread and refresh the UI when it finishes.
546    #[cfg(any(feature = "desktop", feature = "web"))]
547    pub fn run_with(self, on_ready: impl FnOnce(Waker)) -> Result<()> {
548        let feathering_enabled = self.feathering_enabled;
549        let feather_width = self.feather_width;
550        let external_texture_registry = self.external_texture_registry.clone();
551        let initial_window_render_options = self.initial_window_render_options;
552        let runtime = self.build()?;
553        let mut platform = DesktopPlatform::new()
554            .with_feathering_enabled(feathering_enabled)
555            .with_feather_width(feather_width);
556        if let Some(registry) = external_texture_registry {
557            platform.set_external_texture_registry(registry);
558        }
559        if let Some(options) = initial_window_render_options {
560            for window_id in runtime.window_ids() {
561                set_window_render_options(window_id, options);
562            }
563        }
564        let _ = platform.run_with(runtime, on_ready)?;
565        Ok(())
566    }
567
568    #[cfg(all(target_os = "android", feature = "mobile"))]
569    /// Build and run the application in an Android native activity.
570    pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
571        self.run_android_with(android_app, |_| {})
572    }
573
574    #[cfg(all(target_os = "android", feature = "mobile"))]
575    /// Run on Android and invoke `on_ready` with a cross-thread wake handle.
576    pub fn run_android_with(
577        self,
578        android_app: AndroidApp,
579        on_ready: impl FnOnce(Waker),
580    ) -> Result<()> {
581        let feathering_enabled = self.feathering_enabled;
582        let feather_width = self.feather_width;
583        let external_texture_registry = self.external_texture_registry.clone();
584        let initial_window_render_options = self.initial_window_render_options;
585        let runtime = self.build()?;
586        let mut platform = DesktopPlatform::new()
587            .with_feathering_enabled(feathering_enabled)
588            .with_feather_width(feather_width);
589        if let Some(registry) = external_texture_registry {
590            platform.set_external_texture_registry(registry);
591        }
592        if let Some(options) = initial_window_render_options {
593            for window_id in runtime.window_ids() {
594                set_window_render_options(window_id, options);
595            }
596        }
597        let _ = platform.run_android_with(runtime, android_app, on_ready)?;
598        Ok(())
599    }
600
601    #[cfg(not(any(feature = "desktop", feature = "web", feature = "mobile")))]
602    /// Return an error when no platform event-loop feature is enabled.
603    pub fn run(self) -> Result<()> {
604        let _ = self;
605        Err(Error::new(
606            "Application::run requires the `desktop`, `web`, or `mobile` feature to provide a platform event loop",
607        ))
608    }
609}
610
611/// Minimal shared style values for custom facade-level components.
612#[derive(Debug, Clone, PartialEq)]
613pub struct Style {
614    /// Foreground brush used to draw content.
615    pub foreground: Brush,
616    /// Insets around the styled content.
617    pub padding: Padding,
618}
619
620impl Default for Style {
621    fn default() -> Self {
622        let theme = Theme::default();
623
624        Self {
625            foreground: Brush::Solid(theme.foreground),
626            padding: Padding::all(0.0),
627        }
628    }
629}
630
631/// Common imports for ordinary SUI application and widget code.
632pub mod prelude {
633    #[cfg(any(feature = "desktop", feature = "web"))]
634    pub use crate::UiHandle;
635
636    pub use crate::{
637        ActionCard, ActionTilePaint, Align, Alignment, AnimatedValue, AnimationBinding,
638        AnimationDocument, AnimationDocumentFormatError, AnimationEditorCommand,
639        AnimationEditorState, AnimationPlayer, AnimationProperty, AnimationPropertyPath,
640        AnimationSelection, AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind,
641        App, Application, ArrangeCtx, AsyncWakeToken, Axis, Background, Blink, Breadcrumb,
642        BreadcrumbItem, BrowserTabBar, Brush, BrushPreview, BrushPreviewShape, BrushPreviewSpec,
643        BusyIndicator, Button, ButtonAppearance, CalloutPaint, Canvas, CanvasRuler,
644        CanvasRulerAxis, CanvasShape, CanvasStroke, CanvasViewport, Checkbox,
645        CheckboxIndicatorState, ChoiceAppearance, Clip, CodePanelPaint, CodeTextLine,
646        CodeTextPaint, CodeTextSpan, Color, ColorPalette, ColorPaletteSwatch, ColorPicker,
647        ColorSwatch, ComboBox, CommandButtonFill, CommandButtonPaint, CommandGroup, CompiledClip,
648        CompiledTimeline, CompiledTrack, Constraints, ContextMenu, ControlMetrics, ControlPalette,
649        ControlSize, ControlTypography, CoverageDots, CoverageDotsConfig, DataGrid, DateTimeInput,
650        DefaultTheme, DetailRow, Dialog, DisclosureButtonPaint, Divider, Dock, DockPanel,
651        DragDropHost, DragDropScope, DragEvent, DragEventKind, DragOutcome, DragPayload,
652        DragPreview, DragScopeId, DragSessionId, Draggable, Drawer, DropEffect, DropTarget, Easing,
653        EmptyState, EmptyStatePaint, Event, EventCtx, FieldAppearance, FieldGroup, FixedPaneSplit,
654        Flex, FlexAlignContent, FlexBasis, FlexItem, FlexItemLayout, FlexJustify, FlexLayout,
655        FlexLineLayout, FlexStyle, FlexWrap, FloatingViewConfig, FloatingViewSnapshot,
656        FloatingWorkspace, FloatingWorkspaceState, FontFeature, FontFeatures, FontHandle,
657        FontStretch, FontStyle, FontWeight, FormRow, FormSection, FramedField, HairlineEdge, Icon,
658        IconButton, IconButtonPaint, IconGlyph, Image, ImageFit, ImageHandle, ImeEvent, Insets,
659        Interpolate, KeyboardEvent, Keyframe, KeyframeSelection, Label, LayerList, LayerListItem,
660        LayerListReorderChange, LeadingLabelCellPaint, Link, ListItem, ListView, LoopMode,
661        MeasureCtx, MeasuredBottomDock, Menu, MenuItem, Modal, MultilineTextInput, NumberInput,
662        Overflow, PaintCtx, PanelSection, PasswordInput, Path, PathBar, PathBuilder, PixelCanvas,
663        PixelCanvasBlendMode, PixelCanvasBrushShape, PixelCanvasExportSnapshot, PixelCanvasState,
664        PixelCanvasTool, PlacementBadgePaint, PlaybackState, Point, PointerEvent, Popover,
665        PresetStrip, ProgressBar, PropertyRow, PropertyRowLayout, Pulse, RadioButton, RadioGroup,
666        RebuildOnChange, RebuildOnConstraints, Rect, RegisteredFont, RegisteredImage,
667        ReorderableList, ReorderableListChange, ResizablePane, ResourceRegistry, Result, RichText,
668        RichTextSourceMap, RichTextSourceSpan, SampleBatch, SampleBuffer, SampledAnimationValue,
669        ScrollAxes, ScrollBar, ScrollState, ScrollView, SectionLabel, SectionLabelPaint,
670        SectionPanelGeometry, SectionPanelPaint, SegmentedControl, SegmentedControlItem, Select,
671        SelectionChange, SelectionEntry, SelectionIntent, SelectionOrder, SelectionOwnerId,
672        SelectionPayload, SelectionPoint, SelectionScope, SemanticsCtx, Separator, ShapedText,
673        SharedCompiledTimeline, SideSheet, SideSheetPlacement, SingleChild, Size, SizedBox, Slider,
674        SpinBox, Spinner, SplitView, SpringF32, Stack, StatusBar, StatusBarHost, StatusBarSegment,
675        StrokeStyle, Style, Surface, SurfaceAppearance, SurfaceBorder, SurfaceElevation,
676        SurfacePalette, SurfaceRole, Switch, SwitchView, TabBar, Table, TableColumn,
677        TableColumnAlignment, TableRow, Tabs, TextArea, TextBlockPaint, TextCellPaint,
678        TextDocument, TextInput, TextLayout, TextMeasurement, TextParagraph, TextParagraphStyle,
679        TextRenderCoveragePolicy, TextRenderHinting, TextRenderMode, TextRenderPolicy,
680        TextRenderStemDarkening, TextSelectionInfo, TextSpan, TextSpanId, TextStyle,
681        TextSubpixelOrder, TextWrap, Theme, ThemeAspectRatios, ThemeBlurScale, ThemeBreakpoints,
682        ThemeColorScheme, ThemeColors, ThemeContainers, ThemeDensity, ThemeExtension,
683        ThemeExtensions, ThemeFontFamilies, ThemeFontStack, ThemeFontWeights, ThemeLeading,
684        ThemeMotion, ThemePerspective, ThemeRadii, ThemeShadow, ThemeShadowLayer, ThemeShadows,
685        ThemeTextScale, ThemeTextToken, ThemeTracking, Timeline, TimelineBindingSink,
686        TimelinePlayer, TimelineSnap, TimelineTick, TimerToken, ToolPalette, ToolPaletteItem,
687        Toolbar, Tooltip, TooltipAlignment, TooltipPlacement, Track, TrailingSlotRow, Transform,
688        Transition, TreeItem, TreeView, VirtualScrollView, VirtualTable, VirtualTableColumn,
689        VirtualTableRowActivationKind, VirtualTableRowContext, VirtualTableSortDirection,
690        WakeEvent, Widget, WidgetChildren, WidgetPod, WidgetShader, Window, WindowBuilder,
691        WindowRenderOptions, arrange_flex, containers::Padding, detail_row_height_for_value,
692        flex_layout, invalidation_for_animation_property, paint_action_tile, paint_border,
693        paint_callout, paint_checkbox_indicator, paint_code_lines, paint_code_panel,
694        paint_command_button, paint_coverage_dots, paint_coverage_dots_with_config,
695        paint_detail_row_at, paint_disclosure_button, paint_empty_state, paint_hairline,
696        paint_icon_button, paint_leading_label_cell, paint_placement_badge_with,
697        paint_rounded_panel, paint_rounded_rect, paint_section_label, paint_section_label_detail,
698        paint_section_panel, paint_text_block, paint_text_cell, register_builtin_icon_resources,
699        set_window_render_options, wrap_text_lines,
700    };
701}
702
703#[cfg(test)]
704mod tests {
705    use std::sync::Arc;
706
707    use super::{DefaultTheme, HdrThemeMode, HdrThemeTokens, Theme};
708    #[cfg(feature = "wgpu")]
709    use crate::{
710        Application, WgpuExternalTextureRegistry, WindowColorManagementMode,
711        WindowDynamicRangeMode, WindowOutputColorPrimaries, WindowRenderOptions,
712        WindowToneMappingMode,
713    };
714
715    #[derive(Debug, PartialEq)]
716    struct CustomWidgetTheme {
717        radius: f32,
718        density: u8,
719    }
720
721    #[test]
722    fn theme_stores_default_widget_theme_separately_from_extensions() {
723        let mut defaults = DefaultTheme::default();
724        defaults.metrics.min_height = 24.0;
725
726        let theme = Theme::new()
727            .with_default_widgets(defaults)
728            .with_extension(CustomWidgetTheme {
729                radius: 6.0,
730                density: 2,
731            });
732
733        assert_eq!(theme.default_widgets.metrics.min_height, 24.0);
734        assert!(theme.has_extension::<CustomWidgetTheme>());
735        assert_eq!(
736            theme.extension::<CustomWidgetTheme>(),
737            Some(&CustomWidgetTheme {
738                radius: 6.0,
739                density: 2,
740            })
741        );
742    }
743
744    #[test]
745    fn theme_extensions_round_trip_hdr_theme_tokens() {
746        let mut defaults = DefaultTheme::dark();
747        defaults.metrics.min_height = 30.0;
748        defaults.hdr.mode = HdrThemeMode::WideGamutOnly;
749
750        let hdr_tokens = HdrThemeTokens {
751            mode: HdrThemeMode::FullHdr,
752            ..HdrThemeTokens::default()
753        };
754
755        let theme = Theme::new()
756            .with_default_widgets(defaults)
757            .with_extension(hdr_tokens);
758
759        assert_eq!(theme.default_widgets.metrics.min_height, 30.0);
760        assert_eq!(theme.default_widgets.hdr.mode, HdrThemeMode::WideGamutOnly);
761        assert!(theme.has_extension::<HdrThemeTokens>());
762        assert_eq!(theme.extension::<HdrThemeTokens>(), Some(&hdr_tokens));
763        assert_eq!(
764            Arc::as_ref(
765                &theme
766                    .extension_arc::<HdrThemeTokens>()
767                    .expect("hdr theme tokens extension present")
768            ),
769            &hdr_tokens
770        );
771    }
772
773    #[test]
774    fn theme_extensions_support_arc_access_and_removal() {
775        let mut theme = Theme::new();
776        theme.insert_extension(CustomWidgetTheme {
777            radius: 12.0,
778            density: 3,
779        });
780
781        let extension = theme
782            .extension_arc::<CustomWidgetTheme>()
783            .expect("custom widget theme present");
784        assert_eq!(
785            Arc::as_ref(&extension),
786            &CustomWidgetTheme {
787                radius: 12.0,
788                density: 3,
789            }
790        );
791
792        let removed = theme
793            .remove_extension::<CustomWidgetTheme>()
794            .expect("custom widget theme removed");
795        assert_eq!(
796            Arc::as_ref(&removed),
797            &CustomWidgetTheme {
798                radius: 12.0,
799                density: 3,
800            }
801        );
802        assert!(!theme.has_extension::<CustomWidgetTheme>());
803    }
804
805    #[test]
806    fn prelude_exports_rich_text_document_types() {
807        use crate::prelude::*;
808
809        let style = TextStyle::new(Color::WHITE);
810        let document = TextDocument {
811            paragraphs: vec![TextParagraph::from_spans(vec![TextSpan::new(
812                "Hello rich text",
813                style,
814            )])],
815        };
816        let _widget = RichText::new(document);
817        let _theme = DefaultTheme::default().with_density(ThemeDensity::Compact);
818    }
819
820    #[cfg(feature = "wgpu")]
821    #[test]
822    fn application_feather_width_is_configurable() {
823        let options = WindowRenderOptions::new(true, 1.5)
824            .with_color_management_mode(WindowColorManagementMode::PreferHdr)
825            .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
826            .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
827            .with_tone_mapping_mode(WindowToneMappingMode::Reinhard);
828        let app = Application::new()
829            .with_feathering_enabled(false)
830            .with_feather_width(2.25)
831            .with_window_render_options(options);
832        let clamped = Application::new().with_feather_width(-1.0);
833
834        assert!(!app.feathering_enabled());
835        assert_eq!(app.feather_width(), 2.25);
836        assert_eq!(clamped.feather_width(), 0.0);
837        assert_eq!(app.initial_window_render_options(), Some(options));
838    }
839
840    #[cfg(feature = "wgpu")]
841    #[test]
842    fn application_accepts_external_texture_registry() {
843        let registry = WgpuExternalTextureRegistry::new();
844        let app = Application::new().with_external_texture_registry(registry.clone());
845
846        assert!(app.external_texture_registry().is_some());
847        assert!(registry.context().is_none());
848    }
849}