1#![forbid(unsafe_code)]
2
3use std::{
20 any::{Any, TypeId},
21 collections::HashMap,
22 fmt,
23 sync::Arc,
24};
25
26pub mod app;
28pub mod composites;
30pub mod containers;
32pub 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};
54#[allow(deprecated)]
56pub use composites::{BusyIndicator, Drawer, Modal};
57pub use containers::{
58 Align, Background, ContentExtent, Dock, FixedPaneSplit, Flex, MeasuredBottomDock, Overflow,
59 Padding, RebuildOnChange, RebuildOnConstraints, ScrollAxes, ScrollBar, ScrollState, ScrollView,
60 SemanticRegion, SizedBox, Stack, SwitchView, TrailingSlotRow, VirtualScrollView,
61};
62#[allow(deprecated)]
63pub use controls::register_builtin_icon_resources;
64pub use controls::{
65 BUILTIN_ICON_GLYPHS, Button, ButtonAppearance, Checkbox, CheckboxIndicatorState,
66 ChoiceAppearance, DateTimeInput, FieldAppearance, Icon, IconButton, IconButtonPaint, IconGlyph,
67 InteractionPreview, Label, Link, NumberInput, PasswordInput, RadioButton, RadioGroup, Select,
68 Separator, Slider, Switch, TextArea, TextInput, draw_glyph, paint_checkbox_indicator,
69 paint_icon_button,
70};
71#[allow(deprecated)]
73pub use controls::{ComboBox, Divider, MultilineTextInput, SpinBox};
74pub use sui_core::{
75 AsyncWakeToken, Clipboard, ClipboardBackend, Color, ColorSpace, CursorGrabMode, CustomEvent,
76 DirtyRegion, DpiInfo, DragDropScope, DragEvent, DragEventKind, DragOutcome, DragPayload,
77 DragPreview, DragScopeId, DragSessionId, DropEffect, DropEffects, Error, Event, FontHandle,
78 ImageHandle, ImeEvent, InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState,
79 KeyboardEvent, LocalClipboardBackend, Modifiers, MotionPolicy, MotionPreference, Oklch, Path,
80 PathBuilder, PathElement, Point, PointerButton, PointerButtons, PointerEvent, PointerEventKind,
81 PointerKind, RawMouseMotionEvent, Rect, Result, SafeAreaInsets, ScrollDelta, SemanticsAction,
82 SemanticsActionRequest, SemanticsEvent, SemanticsLiveRegion, SemanticsNode, SemanticsPopupKind,
83 SemanticsRelations, SemanticsRole, SemanticsState, SemanticsTextRange, SemanticsValue, Size,
84 SurfaceId, TimerToken, ToggleState, Transform, Vector, WakeEvent, WidgetId, WindowEvent,
85 WindowId,
86};
87pub use sui_layout::Padding as Insets;
88pub use sui_layout::{
89 Alignment, Axis, Constraints, FlexAlignContent, FlexBasis, FlexItem, FlexItemLayout,
90 FlexJustify, FlexLayout, FlexLineLayout, FlexStyle, FlexWrap, GridItem, GridItemLayout,
91 GridLayout, GridPlacement, GridStyle, GridTrack, GridTrackMax, IntrinsicSize, LayoutContext,
92 arrange_flex, flex_layout, grid_layout,
93};
94#[cfg(all(target_os = "android", feature = "mobile"))]
95pub use sui_platform::AndroidApp;
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};
102pub use sui_reactive::{
103 Change as ObservableChange, Observable, Observer, Selector, Signal, SourceId, Subscription,
104 WeakObserver,
105};
106#[cfg(feature = "wgpu")]
107pub use sui_render_wgpu::{
108 DisplayCapabilities, DisplayColorPrimaries, OutputGamut, RendererCapabilities, RendererInterop,
109 RequestedToneMappingMode, RgbaImage, StemDarkening, TextCoveragePolicy, TextHinting,
110 WgpuExternalTextureContext, WgpuExternalTextureRegistry, WgpuRenderer,
111};
112pub use sui_runtime::{
113 AnimateCtx, Application as RuntimeApplication, ArrangeCtx, Command, CommandController,
114 CommandCtx, CommandDelivery, CommandKey, CommandSender, CommandTarget, DEFAULT_SUI_LOGO_SVG,
115 EXTERNAL_WAKE_KIND, EmbeddedSvgImageResource, EventCtx, EventPhase, EventRoutePhase,
116 EventRouteStep, FocusRestorePolicy, FocusScope, FocusScopeState, FocusState, FrameClock,
117 FramePacing, FrameSchedule, KeyedChildren, KeyedReconcile, LayerOptions, MeasureCtx, Motion,
118 OVERLAY_DISMISS_REQUEST, OutputColorRange, OverlayDismissPolicy, OverlayDismissReason,
119 OverlayDismissRequest, OverlayFocusBehavior, OverlayInitialFocus, OverlayKind, OverlayModality,
120 OverlayOptions, PaintBoundaryMode, PaintCtx, REACTIVE_CHANGED, RenderOutput, Runtime,
121 SemanticsCtx, SingleChild, StackHostOptions, StackOrderPolicy, StackSurfaceOptions, Widget,
122 WidgetChildren, WidgetDiagnosticsCtx, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
123 WindowBuilder, WindowColorManagementMode, WindowCursorState, WindowDynamicRangeMode,
124 WindowIcon, WindowOutputColorPrimaries, WindowRenderOptions, WindowStemDarkening,
125 WindowTextCoveragePolicy, WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode,
126 app_motion_preference, clear_window_render_options, default_sui_logo_image, motion_policy,
127 motion_time_scale, reset_motion_settings, set_app_motion_preference, set_motion_time_scale,
128 set_system_motion_preference, set_window_render_options, system_motion_preference,
129 window_output_color_range, window_output_color_range_signal, window_render_options,
130};
131pub use sui_scene::{
132 Border, Brush, GradientStop, ImagePixelSnap, ImageRegistry, ImageSampling, ImageSource,
133 LayerCompositionMode, LayerProperties, RegisteredExternalImage, RegisteredImage,
134 RegisteredImageFormat, Scene, SceneCommand, SceneFrame, ShadowParams, ShadowPlacement,
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, AnimationSpec,
153 AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind, Blink, Clip,
154 CompiledClip, CompiledTimeline, CompiledTrack, Easing, Interpolate, Keyframe,
155 KeyframeSelection, LoopMode, MotionScalar, MotionValue, PlaybackState, Progress, Pulse,
156 SampleBatch, SampleBuffer, SampledAnimationValue, SharedCompiledTimeline, SpringF32,
157 SpringSpec, Timeline, TimelineBindingSink, TimelinePlayer, TimelineSnap, TimelineTick, Track,
158 Transition, invalidation_for_animation_property,
159};
160pub use sui_widgets::animation::{
161 MIN_ANIMATION_DOCUMENT_VERSION, PlaybackSpan, Stagger, StaggerOrigin, TimelineMarker,
162};
163pub use sui_widgets::{
164 ActionCard, AdaptiveBreakpoints, AdaptiveClass, AdaptiveView, AspectRatio, AspectRatioFit,
165 BasicSyntaxHighlighter, Breadcrumb, BreadcrumbItem, BrushPreview, BrushPreviewShape,
166 BrushPreviewSpec, Canvas, CanvasColors, CanvasGridStyle, CanvasRuler, CanvasRulerAxis,
167 CanvasRulerColors, CanvasShape, CanvasStroke, CanvasSurface, CanvasViewport,
168 CanvasZoomBehavior, CanvasZoomContext, CollectionAnchor, CollectionAnchorGravity,
169 CollectionChange, CollectionDelta, CollectionExtentIndex, CollectionModelError, CollectionSync,
170 CollectionWindow, ColorPalette, ColorPaletteSwatch, ColorPicker, ColorPickerColors,
171 ColorSwatch, ConstraintOrientation, ConstraintQuery, ConstraintView, ControlMetrics,
172 ControlPalette, ControlSize, ControlTypography, CoverageDots, CoverageDotsConfig,
173 DecorativeColors, DecorativeHue, DecorativePalette, DefaultTheme, DetailRow, DockFloatingGroup,
174 DockLayoutError, DockNode, DockPanelId, DockWorkspace, DockWorkspaceSnapshot,
175 DockWorkspaceState, DockZone, DragDropHost, Draggable, DropHover, DropTarget, EffectToken,
176 FloatingStack, FloatingViewConfig, FloatingViewSnapshot, FloatingWorkspace,
177 FloatingWorkspaceState, GlowTone, Grid, GridCell, HdrColorRoles, HdrEffectTokens,
178 HdrLuminanceTokens, HdrMaterialTokens, HdrPolicyTokens, HdrThemeMode, HdrThemeTokens, Image,
179 ImageFit, LayerList, LayerListItem, LayerListReorderChange, LayoutTransition,
180 LeadingLabelCellPaint, ListItem, ListView, MasterDetail, MasterDetailRoute, MasterDetailState,
181 MaterialToken, NeutralRamp, NotificationCenter, NotificationHost, NotificationId,
182 NotificationUrgency, OverlayAlignment, OverlayCollisionPolicy, OverlayHost, OverlayPlacement,
183 OverlayPlacementRequest, OverlayPlacementResult, OverlaySide, PixelCanvas,
184 PixelCanvasBlendMode, PixelCanvasBrushShape, PixelCanvasColors, PixelCanvasExportSnapshot,
185 PixelCanvasState, PixelCanvasTool, PlacementBadge, PlacementBadgePaint, ReorderableList,
186 ReorderableListChange, ResolvedEffectStyle, ResolvedHdrStyle, ResolvedMaterialStyle,
187 ResponsiveSidebar, ResponsiveSidebarMode, ResponsiveSidebarSnapshot, ResponsiveSidebarState,
188 RichAttachment, RichBlockId, RichDocumentBlock, RichDocumentBlockKind, RichDocumentModel,
189 RichDocumentRenderContext, RichDocumentRendererRegistry, RichDocumentSnapshot,
190 RichDocumentSpan, RichDocumentStatus, RichDocumentUpdate, RichDocumentView,
191 RichDocumentViewState, RichExtensionBlock, RichInlineImage, RichInlineKind, RichInlineStyle,
192 RichLink, RichListItem, RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind, RichText,
193 RichTextSourceMap, RichTextSourceSpan, SafeArea, SafeAreaEdges, ScrollAlignment,
194 SegmentedControl, SegmentedControlItem, SelectionChange, SelectionClipboardBehavior,
195 SelectionEntry, SelectionIntent, SelectionOrder, SelectionOwnerId, SelectionPayload,
196 SelectionPoint, SelectionScope, SemanticColorToken, SemanticTone, SimpleColorPicker,
197 SimpleColorPickerMode, SplitExtent, SplitPaneSide, SplitState, SplitStateSnapshot, SplitView,
198 StatusBadge, SurfacePalette, TEXT_COMMAND, Table, TableColumn, TableColumnAlignment, TableRow,
199 TextBlockPaint, TextCellPaint, TextCommand, TextSelectionInfo, TextSurface,
200 TextSurfaceOverlayKind, TextSurfaceStatus, TextSurfaceStyleOverlay, TextSurfaceStyleSpan,
201 ThemeAspectRatios, ThemeBlurScale, ThemeBreakpoints, ThemeColorScheme, ThemeColors,
202 ThemeContainers, ThemeDensity, ThemeFontFamilies, ThemeFontStack, ThemeFontWeights, ThemeGlows,
203 ThemeLeading, ThemeMotion, ThemePerspective, ThemeRadii, ThemeShadow, ThemeShadowLayer,
204 ThemeShadows, ThemeTextScale, ThemeTextToken, ThemeTracking, ToneRoles, TransientNotification,
205 TreeItem, TreeView, VirtualCollectionModel, VirtualCollectionSource, VirtualList,
206 VirtualListChrome, VirtualListSelectionMode, VirtualListState, VirtualTable,
207 VirtualTableColumn, VirtualTableRowActivationKind, VirtualTableRowContext,
208 VirtualTableSortDirection, VirtualTableState, VirtualViewportSnapshot, WidgetColorRole,
209 WidgetEffectRole, WidgetLuminanceRole, WidgetMaterialRole, detail_row_height_for_value,
210 paint_canvas_grid, paint_coverage_dots, paint_coverage_dots_with_config, paint_detail_row_at,
211 paint_leading_label_cell, paint_placement_badge, paint_progress_bar, paint_status_badge,
212 paint_text, paint_text_block, paint_text_cell, paint_text_line, paint_theme_glow,
213 paint_theme_inset_shadow, paint_theme_shadow, place_overlay, resolve_effect_role,
214 resolve_luminance_role, resolve_material_role, resolve_semantic_color,
215 resolve_widget_hdr_style, wrap_text_lines,
216};
217#[allow(deprecated)]
219pub use sui_widgets::{
220 CanvasAppearance, CanvasRulerAppearance, ColorPickerAppearance, DataGrid, PathBar,
221 PixelCanvasAppearance, ResizablePane,
222};
223pub use sui_widgets::{KeyedStack, Presence, PresenceTransition};
224pub use sui_widgets::{Paragraph, TextPlacement, TextShaper, VerticalAlign};
225
226pub trait ThemeExtension: Any + Send + Sync {}
228
229impl<T> ThemeExtension for T where T: Any + Send + Sync {}
230
231#[derive(Clone, Default)]
233pub struct ThemeExtensions {
234 values: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
235}
236
237impl ThemeExtensions {
238 pub fn new() -> Self {
240 Self::default()
241 }
242
243 pub fn insert<T>(&mut self, value: T) -> Option<Arc<T>>
245 where
246 T: ThemeExtension,
247 {
248 self.values
249 .insert(TypeId::of::<T>(), Arc::new(value))
250 .and_then(|previous| Arc::downcast::<T>(previous).ok())
251 }
252
253 pub fn get<T>(&self) -> Option<&T>
255 where
256 T: ThemeExtension,
257 {
258 self.values
259 .get(&TypeId::of::<T>())
260 .and_then(|value| value.as_ref().downcast_ref::<T>())
261 }
262
263 pub fn get_arc<T>(&self) -> Option<Arc<T>>
265 where
266 T: ThemeExtension,
267 {
268 self.values
269 .get(&TypeId::of::<T>())
270 .and_then(|value| Arc::clone(value).downcast::<T>().ok())
271 }
272
273 pub fn contains<T>(&self) -> bool
275 where
276 T: ThemeExtension,
277 {
278 self.values.contains_key(&TypeId::of::<T>())
279 }
280
281 pub fn remove<T>(&mut self) -> Option<Arc<T>>
283 where
284 T: ThemeExtension,
285 {
286 self.values
287 .remove(&TypeId::of::<T>())
288 .and_then(|value| Arc::downcast::<T>(value).ok())
289 }
290
291 pub fn is_empty(&self) -> bool {
293 self.values.is_empty()
294 }
295
296 pub fn len(&self) -> usize {
298 self.values.len()
299 }
300}
301
302impl fmt::Debug for ThemeExtensions {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 f.debug_struct("ThemeExtensions")
305 .field("len", &self.values.len())
306 .finish()
307 }
308}
309
310#[derive(Debug, Clone)]
312pub struct Theme {
313 pub background: Color,
315 pub foreground: Color,
317 pub default_widgets: DefaultTheme,
319 pub extensions: ThemeExtensions,
321}
322
323impl Default for Theme {
324 fn default() -> Self {
325 let default_widgets = DefaultTheme::default();
326 Self {
327 background: default_widgets.palette.surface,
328 foreground: default_widgets.palette.text,
329 default_widgets,
330 extensions: ThemeExtensions::default(),
331 }
332 }
333}
334
335impl Theme {
336 pub fn new() -> Self {
338 Self::default()
339 }
340
341 pub fn with_default_widgets(mut self, theme: DefaultTheme) -> Self {
343 self.default_widgets = theme;
344 self
345 }
346
347 pub fn with_extension<T>(mut self, value: T) -> Self
349 where
350 T: ThemeExtension,
351 {
352 self.extensions.insert(value);
353 self
354 }
355
356 pub fn insert_extension<T>(&mut self, value: T) -> Option<Arc<T>>
358 where
359 T: ThemeExtension,
360 {
361 self.extensions.insert(value)
362 }
363
364 pub fn extension<T>(&self) -> Option<&T>
366 where
367 T: ThemeExtension,
368 {
369 self.extensions.get::<T>()
370 }
371
372 pub fn extension_arc<T>(&self) -> Option<Arc<T>>
374 where
375 T: ThemeExtension,
376 {
377 self.extensions.get_arc::<T>()
378 }
379
380 pub fn has_extension<T>(&self) -> bool
382 where
383 T: ThemeExtension,
384 {
385 self.extensions.contains::<T>()
386 }
387
388 pub fn remove_extension<T>(&mut self) -> Option<Arc<T>>
390 where
391 T: ThemeExtension,
392 {
393 self.extensions.remove::<T>()
394 }
395}
396
397pub struct Application {
402 inner: RuntimeApplication,
403 #[cfg(feature = "wgpu")]
404 feathering_enabled: bool,
405 #[cfg(feature = "wgpu")]
406 feather_width: f32,
407 #[cfg(feature = "wgpu")]
408 external_texture_registry: Option<WgpuExternalTextureRegistry>,
409 initial_window_render_options: Option<WindowRenderOptions>,
410}
411
412impl Default for Application {
413 fn default() -> Self {
414 Self {
415 inner: RuntimeApplication::default(),
416 #[cfg(feature = "wgpu")]
417 feathering_enabled: sui_render_wgpu::FeatheringOptions::default().enabled,
418 #[cfg(feature = "wgpu")]
419 feather_width: sui_render_wgpu::FeatheringOptions::default().width,
420 #[cfg(feature = "wgpu")]
421 external_texture_registry: None,
422 initial_window_render_options: None,
423 }
424 }
425}
426
427impl Application {
428 pub fn new() -> Self {
430 Self::default()
431 }
432
433 pub fn window(mut self, window: WindowBuilder) -> Self {
435 self.inner = self.inner.window(window);
436 self
437 }
438
439 pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
441 self.inner = self.inner.controller(controller);
442 self
443 }
444
445 pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
447 where
448 T: Send + Sync + 'static,
449 F: FnMut(&mut CommandCtx, &T) + 'static,
450 {
451 self.inner = self.inner.on_command(key, handler);
452 self
453 }
454
455 #[cfg(feature = "wgpu")]
456 pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
458 self.feathering_enabled = enabled;
459 self
460 }
461
462 #[cfg(feature = "wgpu")]
463 pub fn with_feather_width(mut self, feather_width: f32) -> Self {
465 self.feather_width = feather_width.max(0.0);
466 self
467 }
468
469 #[cfg(feature = "wgpu")]
470 pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
472 self.external_texture_registry = Some(registry);
473 self
474 }
475
476 #[cfg(feature = "wgpu")]
477 pub fn feathering_enabled(&self) -> bool {
479 self.feathering_enabled
480 }
481
482 #[cfg(feature = "wgpu")]
483 pub fn feather_width(&self) -> f32 {
485 self.feather_width
486 }
487
488 #[cfg(feature = "wgpu")]
489 pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
491 self.external_texture_registry.as_ref()
492 }
493
494 pub fn with_window_render_options(mut self, options: WindowRenderOptions) -> Self {
496 self.initial_window_render_options = Some(options.clamped());
497 self
498 }
499
500 pub fn initial_window_render_options(&self) -> Option<WindowRenderOptions> {
502 self.initial_window_render_options
503 }
504
505 pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
507 self.inner.register_font(handle, font)
508 }
509
510 pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
512 self.inner.register_font_bytes(data)
513 }
514
515 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
517 self.inner.register_image(handle, image)
518 }
519
520 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 pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
532 self.inner.register_svg_image(data)
533 }
534
535 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 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 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 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 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 pub fn build(self) -> Result<Runtime> {
584 self.inner.build()
585 }
586
587 #[cfg(any(feature = "desktop", feature = "web"))]
588 pub fn run(self) -> Result<()> {
590 self.run_with_platform(DesktopPlatform::new())
591 }
592
593 #[cfg(any(feature = "desktop", feature = "web"))]
594 pub fn run_with_platform(self, platform: DesktopPlatform) -> Result<()> {
600 self.run_with_platform_and_handle(platform, |_| {})
601 }
602
603 #[cfg(any(feature = "desktop", feature = "web"))]
606 pub fn run_with_platform_and_handle(
607 self,
608 mut platform: DesktopPlatform,
609 on_ready: impl FnOnce(CommandSender),
610 ) -> Result<()> {
611 let feathering_enabled = self.feathering_enabled;
612 let feather_width = self.feather_width;
613 let external_texture_registry = self.external_texture_registry.clone();
614 let initial_window_render_options = self.initial_window_render_options;
615 let runtime = self.build()?;
616 platform.set_feathering_enabled(feathering_enabled);
617 platform.set_feather_width(feather_width);
618 if let Some(registry) = external_texture_registry {
619 platform.set_external_texture_registry(registry);
620 }
621 if let Some(options) = initial_window_render_options {
622 for window_id in runtime.window_ids() {
623 set_window_render_options(window_id, options);
624 }
625 }
626 let _ = platform.run_with(runtime, on_ready)?;
627 Ok(())
628 }
629
630 #[cfg(any(feature = "desktop", feature = "web"))]
633 pub fn run_with(self, on_ready: impl FnOnce(CommandSender)) -> Result<()> {
634 self.run_with_platform_and_handle(DesktopPlatform::new(), on_ready)
635 }
636
637 #[cfg(all(target_os = "android", feature = "mobile"))]
638 pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
640 self.run_android_with(android_app, |_| {})
641 }
642
643 #[cfg(all(target_os = "android", feature = "mobile"))]
644 pub fn run_android_with(
646 self,
647 android_app: AndroidApp,
648 on_ready: impl FnOnce(CommandSender),
649 ) -> Result<()> {
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 let mut platform = DesktopPlatform::new()
656 .with_feathering_enabled(feathering_enabled)
657 .with_feather_width(feather_width);
658 if let Some(registry) = external_texture_registry {
659 platform.set_external_texture_registry(registry);
660 }
661 if let Some(options) = initial_window_render_options {
662 for window_id in runtime.window_ids() {
663 set_window_render_options(window_id, options);
664 }
665 }
666 let _ = platform.run_android_with(runtime, android_app, on_ready)?;
667 Ok(())
668 }
669
670 #[cfg(not(any(feature = "desktop", feature = "web", feature = "mobile")))]
671 pub fn run(self) -> Result<()> {
673 let _ = self;
674 Err(Error::new(
675 "Application::run requires the `desktop`, `web`, or `mobile` feature to provide a platform event loop",
676 ))
677 }
678}
679
680#[deprecated(note = "nothing in SUI reads `Style`; keep such values in your own type")]
682#[derive(Debug, Clone, PartialEq)]
683pub struct Style {
684 pub foreground: Brush,
686 pub padding: Insets,
688}
689
690#[allow(deprecated)]
691impl Default for Style {
692 fn default() -> Self {
693 let theme = Theme::default();
694
695 Self {
696 foreground: Brush::Solid(theme.foreground),
697 padding: Insets::all(0.0),
698 }
699 }
700}
701
702pub mod diagnostics {
707 #[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
708 pub use sui_platform::{
709 AccessibilityIssue, AccessibilityIssueSeverity, AccessibilityIssueTarget,
710 AccessibilitySnapshot, DebugCaptureTicket, DesktopAutomationAction,
711 DesktopAutomationConfig, WindowOutputDiagnostics, request_window_debug_capture,
712 take_window_debug_capture, validate_accessibility_snapshot, window_output_diagnostics,
713 window_output_diagnostics_signal,
714 };
715 #[cfg(feature = "wgpu")]
716 pub use sui_render_wgpu::{
717 DebugCaptureArtifact, DebugCaptureEncoding, DebugCaptureId, DebugCaptureRequest,
718 DebugCaptureStage, DebugSdrVisualization, HdrRgbaImage, OutputStrategy, fit_to_sdr,
719 };
720 pub use sui_runtime::{
721 AsyncTaskInspectorSnapshot, COMMAND_HISTORY_LENGTH, CacheMetrics, CacheMetricsDelta,
722 CommandDispatchSample, EventRouteTraceSample, FramePhase, FramePhaseSample,
723 InspectorHistorySnapshot, InvalidationTraceSample, OverlayManagerSnapshot, OverlaySnapshot,
724 OverlayTraceKind, OverlayTraceSample, PresentationLatencyDiagnostics,
725 ReactiveInvalidationSample, RenderDiagnostics, RendererSubmissionDiagnostics,
726 RetainedPacketRebuildDiagnostics, SceneStatistics, SceneStatisticsDetailMode,
727 SchedulerInspectorSnapshot, TextCacheDeltaDiagnostics, TextCacheDiagnostics,
728 TimerInspectorSnapshot, WidgetDiagnostic, WidgetDiagnosticsSnapshot,
729 WidgetGeometrySnapshot, WidgetGraphSnapshot, WidgetNodeSnapshot, WidgetRebuildSample,
730 WindowInspectorSnapshot, WindowPerformanceSnapshot, WindowPerformanceSummary,
731 set_window_scene_statistics_detail_mode, window_command_dispatches_signal,
732 window_performance_snapshot, window_performance_summary,
733 window_scene_statistics_detail_mode,
734 };
735}
736
737pub mod prelude {
738 #[cfg(any(feature = "desktop", feature = "web"))]
739 pub use crate::UiHandle;
740 #[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
741 pub use crate::{
742 FileDialogFilter, FileDialogMode, FileDialogRequest, FileDialogSelection,
743 FileDialogService, NativeFileDialogs, PlatformFile, show_file_dialog,
744 };
745 #[allow(deprecated)]
747 pub use crate::{
748 BusyIndicator, CanvasAppearance, CanvasRulerAppearance, ColorPickerAppearance, ComboBox,
749 DataGrid, Divider, Drawer, Modal, MultilineTextInput, PathBar, PixelCanvasAppearance,
750 ResizablePane, SpinBox,
751 };
752
753 pub use crate::{
754 ActionCard, AdaptiveBreakpoints, AdaptiveClass, AdaptiveView, Align, Alignment, AnimateCtx,
755 AnimatedValue, AnimationBinding, AnimationDocument, AnimationDocumentFormatError,
756 AnimationPlayer, AnimationProperty, AnimationPropertyPath, AnimationSpec,
757 AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind, App, ArrangeCtx,
758 AspectRatio, AspectRatioFit, AsyncWakeToken, Axis, Background, BasicSyntaxHighlighter,
759 Blink, BottomSheet, Breadcrumb, BreadcrumbItem, BrowserTabBar, Brush, BrushPreview,
760 BrushPreviewShape, BrushPreviewSpec, Button, ButtonAppearance, Canvas, CanvasColors,
761 CanvasGridStyle, CanvasRuler, CanvasRulerAxis, CanvasRulerColors, CanvasShape,
762 CanvasStroke, CanvasSurface, CanvasViewport, CanvasZoomBehavior, CanvasZoomContext,
763 Checkbox, ChoiceAppearance, Clip, CollectionAnchor, CollectionAnchorGravity,
764 CollectionChange, CollectionDelta, CollectionExtentIndex, CollectionModelError,
765 CollectionSync, CollectionWindow, Color, ColorPalette, ColorPaletteSwatch, ColorPicker,
766 ColorPickerColors, ColorSwatch, Command, CommandController, CommandCtx, CommandDelivery,
767 CommandGroup, CommandKey, CommandPalette, CommandSender, CommandTarget,
768 ConstraintOrientation, ConstraintQuery, ConstraintView, Constraints, ContentExtent,
769 ContextMenu, ContextMenuHandle, ControlMetrics, ControlPalette, ControlSize,
770 ControlTypography, CoverageDots, CoverageDotsConfig, CursorGrabMode, DateTimeInput,
771 DecorativeHue, DefaultTheme, DetailRow, Dialog, Dock, DockFloatingGroup, DockLayoutError,
772 DockNode, DockPanel, DockPanelId, DockWorkspace, DockWorkspaceSnapshot, DockWorkspaceState,
773 DockZone, DragDropHost, DragDropScope, DragEvent, DragEventKind, DragOutcome, DragPayload,
774 DragPreview, DragScopeId, DragSessionId, Draggable, DropEffect, DropEffects, DropHover,
775 DropTarget, Easing, EmptyState, Error, Event, EventCtx, EventPhase, FieldAppearance,
776 FieldGroup, FixedPaneSplit, Flex, FlexAlignContent, FlexBasis, FlexItem, FlexJustify,
777 FlexStyle, FlexWrap, FloatingViewConfig, FloatingViewSnapshot, FloatingWorkspace,
778 FloatingWorkspaceState, FocusRestorePolicy, FocusScope, FocusScopeState, FontFeature,
779 FontFeatures, FontHandle, FontStretch, FontStyle, FontWeight, FormRow, FormSection,
780 FrameClock, FramedField, GlowTone, Grid, GridCell, GridItem, GridPlacement, GridStyle,
781 GridTrack, GridTrackMax, Icon, IconButton, IconGlyph, Image, ImageFit, ImageHandle,
782 ImeEvent, Insets, InteractionPreview, Interpolate, IntrinsicSize, KeyState, KeyboardEvent,
783 KeyedChildren, KeyedReconcile, KeyedStack, Keyframe, Label, LayerList, LayerListItem,
784 LayerListReorderChange, LayoutTransition, Link, ListItem, ListView, LoopMode, MasterDetail,
785 MasterDetailRoute, MasterDetailState, MeasureCtx, MeasuredBottomDock, Menu, MenuItem,
786 Modifiers, Motion, MotionPolicy, MotionPreference, MotionScalar, MotionValue, NeutralRamp,
787 NotificationCenter, NotificationHost, NotificationId, NotificationUrgency, NumberInput,
788 Observable, Observer, Overflow, OverlayAlignment, OverlayCollisionPolicy,
789 OverlayDismissPolicy, OverlayDismissReason, OverlayFocusBehavior, OverlayHost, OverlayKind,
790 OverlayOptions, OverlayPlacement, OverlayPlacementRequest, OverlayPlacementResult,
791 OverlaySide, Padding, PaintCtx, PanelSection, PasswordInput, Path, PathBuilder,
792 PixelCanvas, PixelCanvasBlendMode, PixelCanvasBrushShape, PixelCanvasColors,
793 PixelCanvasExportSnapshot, PixelCanvasState, PixelCanvasTool, PlacementBadge,
794 PlaybackState, Point, PointerButton, PointerEvent, Popover, Presence, PresenceTransition,
795 PresetStrip, Progress, ProgressBar, PropertyRow, PropertyRowLayout, Pulse, RadioButton,
796 RadioGroup, RawMouseMotionEvent, RebuildOnChange, RebuildOnConstraints, Rect,
797 RegisteredFont, RegisteredImage, ReorderableList, ReorderableListChange, ResourceRegistry,
798 ResponsiveSidebar, ResponsiveSidebarMode, ResponsiveSidebarSnapshot,
799 ResponsiveSidebarState, Result, RichAttachment, RichBlockId, RichDocumentBlock,
800 RichDocumentBlockKind, RichDocumentModel, RichDocumentRenderContext,
801 RichDocumentRendererRegistry, RichDocumentSnapshot, RichDocumentSpan, RichDocumentStatus,
802 RichDocumentUpdate, RichDocumentView, RichDocumentViewState, RichExtensionBlock,
803 RichInlineImage, RichInlineKind, RichInlineStyle, RichLink, RichListItem,
804 RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind, RichText, RichTextSourceMap,
805 RichTextSourceSpan, SafeArea, SafeAreaEdges, SafeAreaInsets, ScrollAlignment, ScrollAxes,
806 ScrollBar, ScrollState, ScrollView, SectionLabel, SegmentedControl, SegmentedControlItem,
807 Select, SelectionChange, SelectionClipboardBehavior, SelectionEntry, SelectionIntent,
808 SelectionOrder, SelectionOwnerId, SelectionPayload, SelectionPoint, SelectionScope,
809 Selector, SemanticRegion, SemanticTone, SemanticsCtx, Separator, ShadowBox, ShadowParams,
810 ShadowPlacement, ShapedText, SheetState, SideSheet, SideSheetPlacement, Signal,
811 SimpleColorPicker, SimpleColorPickerMode, SingleChild, Size, SizedBox, Slider, SourceId,
812 Spinner, SplitExtent, SplitPaneSide, SplitState, SplitStateSnapshot, SplitView, SpringF32,
813 SpringSpec, Stack, Stagger, StaggerOrigin, StatusBar, StatusBarHost, StatusBarSegment,
814 StrokeStyle, Subscription, Surface, SurfaceAppearance, SurfaceBorder, SurfaceElevation,
815 SurfacePalette, SurfaceRole, Switch, SwitchView, TabBar, TabBarItem, Table, TableColumn,
816 TableColumnAlignment, TableRow, Tabs, TextArea, TextCommand, TextDocument, TextInput,
817 TextLayout, TextMeasurement, TextParagraph, TextParagraphStyle, TextSelectionInfo,
818 TextSpan, TextSpanId, TextStyle, TextWrap, Theme, ThemeAspectRatios, ThemeBlurScale,
819 ThemeBreakpoints, ThemeColorScheme, ThemeColors, ThemeContainers, ThemeDensity,
820 ThemeExtension, ThemeExtensions, ThemeFontFamilies, ThemeFontStack, ThemeFontWeights,
821 ThemeGlows, ThemeLeading, ThemeMotion, ThemePerspective, ThemeRadii, ThemeShadow,
822 ThemeShadowLayer, ThemeShadows, ThemeTextScale, ThemeTextToken, ThemeTracking, Timeline,
823 TimelineMarker, TimelinePlayer, TimelineSnap, TimelineTick, TimerToken, ToolPalette,
824 ToolPaletteItem, Toolbar, Tooltip, TooltipAlignment, TooltipPlacement, Track,
825 TrailingSlotRow, Transform, TransientNotification, Transition, TreeItem, TreeView,
826 VirtualCollectionModel, VirtualCollectionSource, VirtualList, VirtualListChrome,
827 VirtualListSelectionMode, VirtualListState, VirtualScrollView, VirtualTable,
828 VirtualTableColumn, VirtualTableRowActivationKind, VirtualTableRowContext,
829 VirtualTableSortDirection, VirtualTableState, VirtualViewportSnapshot, WakeEvent,
830 WeakObserver, Widget, WidgetChildren, WidgetPod, WidgetShader, Window, WindowCursorState,
831 WindowRenderOptions, paint_text, paint_text_line,
832 };
833 pub use crate::{Paragraph, TextAlign, TextPlacement, TextShaper, VerticalAlign};
834}
835
836#[cfg(test)]
837mod tests {
838 use std::sync::Arc;
839
840 use super::{DefaultTheme, HdrThemeMode, HdrThemeTokens, Theme};
841 #[cfg(feature = "wgpu")]
842 use crate::{
843 Application, WgpuExternalTextureRegistry, WindowColorManagementMode,
844 WindowDynamicRangeMode, WindowOutputColorPrimaries, WindowRenderOptions,
845 WindowToneMappingMode,
846 };
847
848 #[derive(Debug, PartialEq)]
849 struct CustomWidgetTheme {
850 radius: f32,
851 density: u8,
852 }
853
854 #[test]
855 fn theme_stores_default_widget_theme_separately_from_extensions() {
856 let mut defaults = DefaultTheme::default();
857 defaults.metrics.min_height = 24.0;
858
859 let theme = Theme::new()
860 .with_default_widgets(defaults)
861 .with_extension(CustomWidgetTheme {
862 radius: 6.0,
863 density: 2,
864 });
865
866 assert_eq!(theme.default_widgets.metrics.min_height, 24.0);
867 assert!(theme.has_extension::<CustomWidgetTheme>());
868 assert_eq!(
869 theme.extension::<CustomWidgetTheme>(),
870 Some(&CustomWidgetTheme {
871 radius: 6.0,
872 density: 2,
873 })
874 );
875 }
876
877 #[test]
878 fn theme_extensions_round_trip_hdr_theme_tokens() {
879 let mut defaults = DefaultTheme::dark();
880 defaults.metrics.min_height = 30.0;
881 defaults.hdr.mode = HdrThemeMode::WideGamutOnly;
882
883 let hdr_tokens = HdrThemeTokens {
884 mode: HdrThemeMode::FullHdr,
885 ..HdrThemeTokens::default()
886 };
887
888 let theme = Theme::new()
889 .with_default_widgets(defaults)
890 .with_extension(hdr_tokens);
891
892 assert_eq!(theme.default_widgets.metrics.min_height, 30.0);
893 assert_eq!(theme.default_widgets.hdr.mode, HdrThemeMode::WideGamutOnly);
894 assert!(theme.has_extension::<HdrThemeTokens>());
895 assert_eq!(theme.extension::<HdrThemeTokens>(), Some(&hdr_tokens));
896 assert_eq!(
897 Arc::as_ref(
898 &theme
899 .extension_arc::<HdrThemeTokens>()
900 .expect("hdr theme tokens extension present")
901 ),
902 &hdr_tokens
903 );
904 }
905
906 #[test]
907 fn theme_extensions_support_arc_access_and_removal() {
908 let mut theme = Theme::new();
909 theme.insert_extension(CustomWidgetTheme {
910 radius: 12.0,
911 density: 3,
912 });
913
914 let extension = theme
915 .extension_arc::<CustomWidgetTheme>()
916 .expect("custom widget theme present");
917 assert_eq!(
918 Arc::as_ref(&extension),
919 &CustomWidgetTheme {
920 radius: 12.0,
921 density: 3,
922 }
923 );
924
925 let removed = theme
926 .remove_extension::<CustomWidgetTheme>()
927 .expect("custom widget theme removed");
928 assert_eq!(
929 Arc::as_ref(&removed),
930 &CustomWidgetTheme {
931 radius: 12.0,
932 density: 3,
933 }
934 );
935 assert!(!theme.has_extension::<CustomWidgetTheme>());
936 }
937
938 #[test]
939 fn prelude_exports_rich_text_document_types() {
940 use crate::prelude::*;
941
942 let style = TextStyle::new(Color::WHITE);
943 let document = TextDocument {
944 paragraphs: vec![TextParagraph::from_spans(vec![TextSpan::new(
945 "Hello rich text",
946 style,
947 )])],
948 };
949 let _widget = RichText::new(document);
950 let _theme = DefaultTheme::default().with_density(ThemeDensity::Compact);
951 }
952
953 #[cfg(feature = "wgpu")]
954 #[test]
955 fn application_feather_width_is_configurable() {
956 let options = WindowRenderOptions::new(true, 1.5)
957 .with_color_management_mode(WindowColorManagementMode::PreferHdr)
958 .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
959 .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
960 .with_tone_mapping_mode(WindowToneMappingMode::Reinhard);
961 let app = Application::new()
962 .with_feathering_enabled(false)
963 .with_feather_width(2.25)
964 .with_window_render_options(options);
965 let clamped = Application::new().with_feather_width(-1.0);
966
967 assert!(!app.feathering_enabled());
968 assert_eq!(app.feather_width(), 2.25);
969 assert_eq!(clamped.feather_width(), 0.0);
970 assert_eq!(app.initial_window_render_options(), Some(options));
971 }
972
973 #[cfg(feature = "wgpu")]
974 #[test]
975 fn application_accepts_external_texture_registry() {
976 let registry = WgpuExternalTextureRegistry::new();
977 let app = Application::new().with_external_texture_registry(registry.clone());
978
979 assert!(app.external_texture_registry().is_some());
980 assert!(registry.context().is_none());
981 }
982}