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