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