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