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