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(all(
97 feature = "desktop",
98 any(target_os = "windows", target_os = "macos", target_os = "linux")
99))]
100pub use sui_platform::OsClipboardBackend;
101#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
102pub use sui_platform::{
103 DesktopExtension, DesktopExtensionContext, DesktopPlatform, DesktopWindow, FileDialogFilter,
104 FileDialogFuture, FileDialogMode, FileDialogRequest, FileDialogSelection, FileDialogService,
105 HeadlessPlatform, NativeFileDialogs, PlatformFile, PlatformWindow, Waker, show_file_dialog,
106};
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};
222#[allow(deprecated)]
224pub use sui_widgets::{
225 CanvasAppearance, CanvasRulerAppearance, ColorPickerAppearance, DataGrid, PathBar,
226 PixelCanvasAppearance, ResizablePane,
227};
228pub use sui_widgets::{KeyedStack, Presence, PresenceTransition};
229pub use sui_widgets::{Paragraph, TextPlacement, TextShaper, VerticalAlign};
230
231pub trait ThemeExtension: Any + Send + Sync {}
233
234impl<T> ThemeExtension for T where T: Any + Send + Sync {}
235
236#[derive(Clone, Default)]
238pub struct ThemeExtensions {
239 values: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
240}
241
242impl ThemeExtensions {
243 pub fn new() -> Self {
245 Self::default()
246 }
247
248 pub fn insert<T>(&mut self, value: T) -> Option<Arc<T>>
250 where
251 T: ThemeExtension,
252 {
253 self.values
254 .insert(TypeId::of::<T>(), Arc::new(value))
255 .and_then(|previous| Arc::downcast::<T>(previous).ok())
256 }
257
258 pub fn get<T>(&self) -> Option<&T>
260 where
261 T: ThemeExtension,
262 {
263 self.values
264 .get(&TypeId::of::<T>())
265 .and_then(|value| value.as_ref().downcast_ref::<T>())
266 }
267
268 pub fn get_arc<T>(&self) -> Option<Arc<T>>
270 where
271 T: ThemeExtension,
272 {
273 self.values
274 .get(&TypeId::of::<T>())
275 .and_then(|value| Arc::clone(value).downcast::<T>().ok())
276 }
277
278 pub fn contains<T>(&self) -> bool
280 where
281 T: ThemeExtension,
282 {
283 self.values.contains_key(&TypeId::of::<T>())
284 }
285
286 pub fn remove<T>(&mut self) -> Option<Arc<T>>
288 where
289 T: ThemeExtension,
290 {
291 self.values
292 .remove(&TypeId::of::<T>())
293 .and_then(|value| Arc::downcast::<T>(value).ok())
294 }
295
296 pub fn is_empty(&self) -> bool {
298 self.values.is_empty()
299 }
300
301 pub fn len(&self) -> usize {
303 self.values.len()
304 }
305}
306
307impl fmt::Debug for ThemeExtensions {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 f.debug_struct("ThemeExtensions")
310 .field("len", &self.values.len())
311 .finish()
312 }
313}
314
315#[derive(Debug, Clone)]
317pub struct Theme {
318 pub background: Color,
320 pub foreground: Color,
322 pub default_widgets: DefaultTheme,
324 pub extensions: ThemeExtensions,
326}
327
328impl Default for Theme {
329 fn default() -> Self {
330 let default_widgets = DefaultTheme::default();
331 Self {
332 background: default_widgets.palette.surface,
333 foreground: default_widgets.palette.text,
334 default_widgets,
335 extensions: ThemeExtensions::default(),
336 }
337 }
338}
339
340impl Theme {
341 pub fn new() -> Self {
343 Self::default()
344 }
345
346 pub fn with_default_widgets(mut self, theme: DefaultTheme) -> Self {
348 self.default_widgets = theme;
349 self
350 }
351
352 pub fn with_extension<T>(mut self, value: T) -> Self
354 where
355 T: ThemeExtension,
356 {
357 self.extensions.insert(value);
358 self
359 }
360
361 pub fn insert_extension<T>(&mut self, value: T) -> Option<Arc<T>>
363 where
364 T: ThemeExtension,
365 {
366 self.extensions.insert(value)
367 }
368
369 pub fn extension<T>(&self) -> Option<&T>
371 where
372 T: ThemeExtension,
373 {
374 self.extensions.get::<T>()
375 }
376
377 pub fn extension_arc<T>(&self) -> Option<Arc<T>>
379 where
380 T: ThemeExtension,
381 {
382 self.extensions.get_arc::<T>()
383 }
384
385 pub fn has_extension<T>(&self) -> bool
387 where
388 T: ThemeExtension,
389 {
390 self.extensions.contains::<T>()
391 }
392
393 pub fn remove_extension<T>(&mut self) -> Option<Arc<T>>
395 where
396 T: ThemeExtension,
397 {
398 self.extensions.remove::<T>()
399 }
400}
401
402pub struct Application {
407 inner: RuntimeApplication,
408 #[cfg(feature = "wgpu")]
409 feathering_enabled: bool,
410 #[cfg(feature = "wgpu")]
411 feather_width: f32,
412 #[cfg(feature = "wgpu")]
413 external_texture_registry: Option<WgpuExternalTextureRegistry>,
414 initial_window_render_options: Option<WindowRenderOptions>,
415}
416
417impl Default for Application {
418 fn default() -> Self {
419 Self {
420 inner: RuntimeApplication::default(),
421 #[cfg(feature = "wgpu")]
422 feathering_enabled: sui_render_wgpu::FeatheringOptions::default().enabled,
423 #[cfg(feature = "wgpu")]
424 feather_width: sui_render_wgpu::FeatheringOptions::default().width,
425 #[cfg(feature = "wgpu")]
426 external_texture_registry: None,
427 initial_window_render_options: None,
428 }
429 }
430}
431
432impl Application {
433 pub fn new() -> Self {
435 Self::default()
436 }
437
438 pub fn window(mut self, window: WindowBuilder) -> Self {
440 self.inner = self.inner.window(window);
441 self
442 }
443
444 pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
446 self.inner = self.inner.controller(controller);
447 self
448 }
449
450 pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
452 where
453 T: Send + Sync + 'static,
454 F: FnMut(&mut CommandCtx, &T) + 'static,
455 {
456 self.inner = self.inner.on_command(key, handler);
457 self
458 }
459
460 #[cfg(feature = "wgpu")]
461 pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
463 self.feathering_enabled = enabled;
464 self
465 }
466
467 #[cfg(feature = "wgpu")]
468 pub fn with_feather_width(mut self, feather_width: f32) -> Self {
470 self.feather_width = feather_width.max(0.0);
471 self
472 }
473
474 #[cfg(feature = "wgpu")]
475 pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
477 self.external_texture_registry = Some(registry);
478 self
479 }
480
481 #[cfg(feature = "wgpu")]
482 pub fn feathering_enabled(&self) -> bool {
484 self.feathering_enabled
485 }
486
487 #[cfg(feature = "wgpu")]
488 pub fn feather_width(&self) -> f32 {
490 self.feather_width
491 }
492
493 #[cfg(feature = "wgpu")]
494 pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
496 self.external_texture_registry.as_ref()
497 }
498
499 pub fn with_window_render_options(mut self, options: WindowRenderOptions) -> Self {
501 self.initial_window_render_options = Some(options.clamped());
502 self
503 }
504
505 pub fn initial_window_render_options(&self) -> Option<WindowRenderOptions> {
507 self.initial_window_render_options
508 }
509
510 pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
512 self.inner.register_font(handle, font)
513 }
514
515 pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
517 self.inner.register_font_bytes(data)
518 }
519
520 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
522 self.inner.register_image(handle, image)
523 }
524
525 pub fn register_rgba_image(
527 &mut self,
528 width: u32,
529 height: u32,
530 data: impl Into<Vec<u8>>,
531 ) -> Result<ImageHandle> {
532 self.inner.register_rgba_image(width, height, data)
533 }
534
535 pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
537 self.inner.register_svg_image(data)
538 }
539
540 pub fn register_svg_image_with_handle(
542 &mut self,
543 handle: ImageHandle,
544 data: impl AsRef<[u8]>,
545 ) -> Result<()> {
546 self.inner.register_svg_image_with_handle(handle, data)
547 }
548
549 pub fn register_svg_image_at_size(
551 &mut self,
552 width: u32,
553 height: u32,
554 data: impl AsRef<[u8]>,
555 ) -> Result<ImageHandle> {
556 self.inner.register_svg_image_at_size(width, height, data)
557 }
558
559 pub fn register_svg_image_at_size_with_handle(
561 &mut self,
562 handle: ImageHandle,
563 width: u32,
564 height: u32,
565 data: impl AsRef<[u8]>,
566 ) -> Result<()> {
567 self.inner
568 .register_svg_image_at_size_with_handle(handle, width, height, data)
569 }
570
571 pub fn register_embedded_svg_image(
573 &mut self,
574 resource: EmbeddedSvgImageResource,
575 ) -> Result<()> {
576 self.inner.register_embedded_svg_image(resource)
577 }
578
579 pub fn register_embedded_svg_images(
581 &mut self,
582 resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
583 ) -> Result<()> {
584 self.inner.register_embedded_svg_images(resources)
585 }
586
587 pub fn build(self) -> Result<Runtime> {
589 self.inner.build()
590 }
591
592 #[cfg(any(feature = "desktop", feature = "web"))]
593 pub fn run(self) -> Result<()> {
595 self.run_with_platform(DesktopPlatform::new())
596 }
597
598 #[cfg(any(feature = "desktop", feature = "web"))]
599 pub fn run_with_platform(self, platform: DesktopPlatform) -> Result<()> {
605 self.run_with_platform_and_handle(platform, |_| {})
606 }
607
608 #[cfg(any(feature = "desktop", feature = "web"))]
611 pub fn run_with_platform_and_handle(
612 self,
613 mut platform: DesktopPlatform,
614 on_ready: impl FnOnce(CommandSender),
615 ) -> Result<()> {
616 let feathering_enabled = self.feathering_enabled;
617 let feather_width = self.feather_width;
618 let external_texture_registry = self.external_texture_registry.clone();
619 let initial_window_render_options = self.initial_window_render_options;
620 let runtime = self.build()?;
621 platform.set_feathering_enabled(feathering_enabled);
622 platform.set_feather_width(feather_width);
623 if let Some(registry) = external_texture_registry {
624 platform.set_external_texture_registry(registry);
625 }
626 if let Some(options) = initial_window_render_options {
627 for window_id in runtime.window_ids() {
628 set_window_render_options(window_id, options);
629 }
630 }
631 let _ = platform.run_with(runtime, on_ready)?;
632 Ok(())
633 }
634
635 #[cfg(any(feature = "desktop", feature = "web"))]
638 pub fn run_with(self, on_ready: impl FnOnce(CommandSender)) -> Result<()> {
639 self.run_with_platform_and_handle(DesktopPlatform::new(), on_ready)
640 }
641
642 #[cfg(all(target_os = "android", feature = "mobile"))]
643 pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
645 self.run_android_with(android_app, |_| {})
646 }
647
648 #[cfg(all(target_os = "android", feature = "mobile"))]
649 pub fn run_android_with(
651 self,
652 android_app: AndroidApp,
653 on_ready: impl FnOnce(CommandSender),
654 ) -> Result<()> {
655 let feathering_enabled = self.feathering_enabled;
656 let feather_width = self.feather_width;
657 let external_texture_registry = self.external_texture_registry.clone();
658 let initial_window_render_options = self.initial_window_render_options;
659 let runtime = self.build()?;
660 let mut platform = DesktopPlatform::new()
661 .with_feathering_enabled(feathering_enabled)
662 .with_feather_width(feather_width);
663 if let Some(registry) = external_texture_registry {
664 platform.set_external_texture_registry(registry);
665 }
666 if let Some(options) = initial_window_render_options {
667 for window_id in runtime.window_ids() {
668 set_window_render_options(window_id, options);
669 }
670 }
671 let _ = platform.run_android_with(runtime, android_app, on_ready)?;
672 Ok(())
673 }
674
675 #[cfg(not(any(feature = "desktop", feature = "web", feature = "mobile")))]
676 pub fn run(self) -> Result<()> {
678 let _ = self;
679 Err(Error::new(
680 "Application::run requires the `desktop`, `web`, or `mobile` feature to provide a platform event loop",
681 ))
682 }
683}
684
685#[deprecated(note = "nothing in SUI reads `Style`; keep such values in your own type")]
687#[derive(Debug, Clone, PartialEq)]
688pub struct Style {
689 pub foreground: Brush,
691 pub padding: Insets,
693}
694
695#[allow(deprecated)]
696impl Default for Style {
697 fn default() -> Self {
698 let theme = Theme::default();
699
700 Self {
701 foreground: Brush::Solid(theme.foreground),
702 padding: Insets::all(0.0),
703 }
704 }
705}
706
707pub mod diagnostics {
712 #[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
713 pub use sui_platform::{
714 AccessibilityIssue, AccessibilityIssueSeverity, AccessibilityIssueTarget,
715 AccessibilitySnapshot, DebugCaptureTicket, DesktopAutomationAction,
716 DesktopAutomationConfig, WindowOutputDiagnostics, request_window_debug_capture,
717 take_window_debug_capture, validate_accessibility_snapshot, window_output_diagnostics,
718 window_output_diagnostics_signal,
719 };
720 #[cfg(feature = "wgpu")]
721 pub use sui_render_wgpu::{
722 DebugCaptureArtifact, DebugCaptureEncoding, DebugCaptureId, DebugCaptureRequest,
723 DebugCaptureStage, DebugSdrVisualization, HdrRgbaImage, OutputStrategy, fit_to_sdr,
724 };
725 pub use sui_runtime::{
726 AsyncTaskInspectorSnapshot, COMMAND_HISTORY_LENGTH, CacheMetrics, CacheMetricsDelta,
727 CommandDispatchSample, EventRouteTraceSample, FramePhase, FramePhaseSample,
728 InspectorHistorySnapshot, InvalidationTraceSample, OverlayManagerSnapshot, OverlaySnapshot,
729 OverlayTraceKind, OverlayTraceSample, PresentationLatencyDiagnostics,
730 ReactiveInvalidationSample, RenderDiagnostics, RendererSubmissionDiagnostics,
731 RetainedPacketRebuildDiagnostics, SceneStatistics, SceneStatisticsDetailMode,
732 SchedulerInspectorSnapshot, TextCacheDeltaDiagnostics, TextCacheDiagnostics,
733 TimerInspectorSnapshot, WidgetDiagnostic, WidgetDiagnosticsSnapshot,
734 WidgetGeometrySnapshot, WidgetGraphSnapshot, WidgetNodeSnapshot, WidgetRebuildSample,
735 WindowInspectorSnapshot, WindowPerformanceSnapshot, WindowPerformanceSummary,
736 set_window_scene_statistics_detail_mode, window_command_dispatches_signal,
737 window_performance_snapshot, window_performance_summary,
738 window_scene_statistics_detail_mode,
739 };
740}
741
742pub mod prelude {
743 #[cfg(any(feature = "desktop", feature = "web"))]
744 pub use crate::UiHandle;
745 #[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
746 pub use crate::{
747 FileDialogFilter, FileDialogMode, FileDialogRequest, FileDialogSelection,
748 FileDialogService, NativeFileDialogs, PlatformFile, show_file_dialog,
749 };
750 #[allow(deprecated)]
752 pub use crate::{
753 BusyIndicator, CanvasAppearance, CanvasRulerAppearance, ColorPickerAppearance, ComboBox,
754 DataGrid, Divider, Drawer, Modal, MultilineTextInput, PathBar, PixelCanvasAppearance,
755 ResizablePane, SpinBox,
756 };
757
758 pub use crate::{
759 ActionCard, AdaptiveBreakpoints, AdaptiveClass, AdaptiveView, Align, Alignment, AnimateCtx,
760 AnimatedValue, AnimationBinding, AnimationDocument, AnimationDocumentFormatError,
761 AnimationPlayer, AnimationProperty, AnimationPropertyPath, AnimationSpec,
762 AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind, App, ArrangeCtx,
763 AspectRatio, AspectRatioFit, AsyncWakeToken, Axis, Background, BasicSyntaxHighlighter,
764 Blink, BottomSheet, Breadcrumb, BreadcrumbItem, BrowserTabBar, Brush, BrushPreview,
765 BrushPreviewShape, BrushPreviewSpec, Button, ButtonAppearance, Canvas, CanvasColors,
766 CanvasGridStyle, CanvasRuler, CanvasRulerAxis, CanvasRulerColors, CanvasShape,
767 CanvasStroke, CanvasSurface, CanvasViewport, CanvasZoomBehavior, CanvasZoomContext,
768 Checkbox, ChoiceAppearance, Clip, CollectionAnchor, CollectionAnchorGravity,
769 CollectionChange, CollectionDelta, CollectionExtentIndex, CollectionModelError,
770 CollectionSync, CollectionWindow, Color, ColorPalette, ColorPaletteSwatch, ColorPicker,
771 ColorPickerColors, ColorSwatch, Command, CommandController, CommandCtx, CommandDelivery,
772 CommandGroup, CommandKey, CommandPalette, CommandSender, CommandTarget,
773 ConstraintOrientation, ConstraintQuery, ConstraintView, Constraints, ContentExtent,
774 ContextMenu, ContextMenuHandle, ControlMetrics, ControlPalette, ControlSize,
775 ControlTypography, CoverageDots, CoverageDotsConfig, CursorGrabMode, DateTimeInput,
776 DecorativeHue, DefaultTheme, DetailRow, Dialog, Dock, DockFloatingGroup, DockLayoutError,
777 DockNode, DockPanel, DockPanelId, DockWorkspace, DockWorkspaceSnapshot, DockWorkspaceState,
778 DockZone, DragDropHost, DragDropScope, DragEvent, DragEventKind, DragOutcome, DragPayload,
779 DragPreview, DragScopeId, DragSessionId, Draggable, DropEffect, DropEffects, DropHover,
780 DropTarget, Easing, EmptyState, Error, Event, EventCtx, EventPhase, FieldAppearance,
781 FieldGroup, FixedPaneSplit, Flex, FlexAlignContent, FlexBasis, FlexItem, FlexJustify,
782 FlexStyle, FlexWrap, FloatingViewConfig, FloatingViewSnapshot, FloatingWorkspace,
783 FloatingWorkspaceState, FocusRestorePolicy, FocusScope, FocusScopeState, FontFeature,
784 FontFeatures, FontHandle, FontStretch, FontStyle, FontWeight, FormRow, FormSection,
785 FrameClock, FramedField, GlowTone, Grid, GridCell, GridItem, GridPlacement, GridStyle,
786 GridTrack, GridTrackMax, Icon, IconButton, IconGlyph, Image, ImageFit, ImageHandle,
787 ImeEvent, Insets, InteractionPreview, Interpolate, IntrinsicSize, KeyState, KeyboardEvent,
788 KeyedChildren, KeyedReconcile, KeyedStack, Keyframe, Label, LayerList, LayerListItem,
789 LayerListReorderChange, LayoutTransition, Link, ListItem, ListView, LoopMode, MasterDetail,
790 MasterDetailRoute, MasterDetailState, MeasureCtx, MeasuredBottomDock, Menu, MenuItem,
791 Modifiers, Motion, MotionPolicy, MotionPreference, MotionScalar, MotionValue, NeutralRamp,
792 NotificationCenter, NotificationHost, NotificationId, NotificationUrgency, NumberInput,
793 Observable, Observer, Overflow, OverlayAlignment, OverlayCollisionPolicy,
794 OverlayDismissPolicy, OverlayDismissReason, OverlayFocusBehavior, OverlayHost, OverlayKind,
795 OverlayOptions, OverlayPlacement, OverlayPlacementRequest, OverlayPlacementResult,
796 OverlaySide, Padding, PaintCtx, PanelSection, PasswordInput, Path, PathBuilder,
797 PixelCanvas, PixelCanvasBlendMode, PixelCanvasBrushShape, PixelCanvasColors,
798 PixelCanvasExportSnapshot, PixelCanvasState, PixelCanvasTool, PlacementBadge,
799 PlaybackState, Point, PointerButton, PointerEvent, Popover, Presence, PresenceTransition,
800 PresetStrip, Progress, ProgressBar, PropertyRow, PropertyRowLayout, Pulse, RadioButton,
801 RadioGroup, RawMouseMotionEvent, RebuildOnChange, RebuildOnConstraints, Rect,
802 RegisteredFont, RegisteredImage, ReorderableList, ReorderableListChange, ResourceRegistry,
803 ResponsiveSidebar, ResponsiveSidebarMode, ResponsiveSidebarSnapshot,
804 ResponsiveSidebarState, Result, RichAttachment, RichBlockId, RichDocumentBlock,
805 RichDocumentBlockKind, RichDocumentModel, RichDocumentRenderContext,
806 RichDocumentRendererRegistry, RichDocumentSnapshot, RichDocumentSpan, RichDocumentStatus,
807 RichDocumentUpdate, RichDocumentView, RichDocumentViewState, RichExtensionBlock,
808 RichInlineImage, RichInlineKind, RichInlineStyle, RichLink, RichListItem,
809 RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind, RichText, RichTextSourceMap,
810 RichTextSourceSpan, SafeArea, SafeAreaEdges, SafeAreaInsets, ScrollAlignment, ScrollAxes,
811 ScrollBar, ScrollState, ScrollView, SectionLabel, SegmentedControl, SegmentedControlItem,
812 Select, SelectionChange, SelectionClipboardBehavior, SelectionEntry, SelectionIntent,
813 SelectionOrder, SelectionOwnerId, SelectionPayload, SelectionPoint, SelectionScope,
814 Selector, SemanticRegion, SemanticTone, SemanticsCtx, Separator, ShadowBox, ShadowParams,
815 ShadowPlacement, ShapedText, SheetState, SideSheet, SideSheetPlacement, Signal,
816 SimpleColorPicker, SimpleColorPickerMode, SingleChild, Size, SizedBox, Slider, SourceId,
817 Spinner, SplitExtent, SplitPaneSide, SplitState, SplitStateSnapshot, SplitView, SpringF32,
818 SpringSpec, Stack, Stagger, StaggerOrigin, StatusBar, StatusBarHost, StatusBarSegment,
819 StrokeStyle, Subscription, Surface, SurfaceAppearance, SurfaceBorder, SurfaceElevation,
820 SurfacePalette, SurfaceRole, Switch, SwitchView, TabBar, TabBarItem, Table, TableColumn,
821 TableColumnAlignment, TableRow, Tabs, Task, TaskHandle, TaskState, TextArea, TextCommand,
822 TextDocument, TextInput, TextLayout, TextMeasurement, TextParagraph, TextParagraphStyle,
823 TextSelectionInfo, TextSpan, TextSpanId, TextStyle, TextWrap, Theme, ThemeAspectRatios,
824 ThemeBlurScale, ThemeBreakpoints, ThemeColorScheme, ThemeColors, ThemeContainers,
825 ThemeDensity, ThemeExtension, ThemeExtensions, ThemeFontFamilies, ThemeFontStack,
826 ThemeFontWeights, ThemeGlows, ThemeLeading, ThemeMotion, ThemePerspective, ThemeRadii,
827 ThemeShadow, ThemeShadowLayer, ThemeShadows, ThemeTextScale, ThemeTextToken, ThemeTracking,
828 Timeline, TimelineMarker, TimelinePlayer, TimelineSnap, TimelineTick, TimerToken,
829 ToolPalette, ToolPaletteItem, Toolbar, Tooltip, TooltipAlignment, TooltipPlacement, Track,
830 TrailingSlotRow, Transform, TransientNotification, Transition, TreeItem, TreeView,
831 VirtualCollectionModel, VirtualCollectionSource, VirtualList, VirtualListChrome,
832 VirtualListSelectionMode, VirtualListState, VirtualScrollView, VirtualTable,
833 VirtualTableColumn, VirtualTableRowActivationKind, VirtualTableRowContext,
834 VirtualTableSortDirection, VirtualTableState, VirtualViewportSnapshot, WakeEvent,
835 WeakObserver, Widget, WidgetChildren, WidgetPod, WidgetShader, Window, WindowCursorState,
836 WindowRenderOptions, paint_text, paint_text_line,
837 };
838 pub use crate::{Paragraph, TextAlign, TextPlacement, TextShaper, VerticalAlign};
839}
840
841#[cfg(test)]
842mod tests {
843 use std::sync::Arc;
844
845 use super::{DefaultTheme, HdrThemeMode, HdrThemeTokens, Theme};
846 #[cfg(feature = "wgpu")]
847 use crate::{
848 Application, WgpuExternalTextureRegistry, WindowColorManagementMode,
849 WindowDynamicRangeMode, WindowOutputColorPrimaries, WindowRenderOptions,
850 WindowToneMappingMode,
851 };
852
853 #[derive(Debug, PartialEq)]
854 struct CustomWidgetTheme {
855 radius: f32,
856 density: u8,
857 }
858
859 #[test]
860 fn theme_stores_default_widget_theme_separately_from_extensions() {
861 let mut defaults = DefaultTheme::default();
862 defaults.metrics.min_height = 24.0;
863
864 let theme = Theme::new()
865 .with_default_widgets(defaults)
866 .with_extension(CustomWidgetTheme {
867 radius: 6.0,
868 density: 2,
869 });
870
871 assert_eq!(theme.default_widgets.metrics.min_height, 24.0);
872 assert!(theme.has_extension::<CustomWidgetTheme>());
873 assert_eq!(
874 theme.extension::<CustomWidgetTheme>(),
875 Some(&CustomWidgetTheme {
876 radius: 6.0,
877 density: 2,
878 })
879 );
880 }
881
882 #[test]
883 fn theme_extensions_round_trip_hdr_theme_tokens() {
884 let mut defaults = DefaultTheme::dark();
885 defaults.metrics.min_height = 30.0;
886 defaults.hdr.mode = HdrThemeMode::WideGamutOnly;
887
888 let hdr_tokens = HdrThemeTokens {
889 mode: HdrThemeMode::FullHdr,
890 ..HdrThemeTokens::default()
891 };
892
893 let theme = Theme::new()
894 .with_default_widgets(defaults)
895 .with_extension(hdr_tokens);
896
897 assert_eq!(theme.default_widgets.metrics.min_height, 30.0);
898 assert_eq!(theme.default_widgets.hdr.mode, HdrThemeMode::WideGamutOnly);
899 assert!(theme.has_extension::<HdrThemeTokens>());
900 assert_eq!(theme.extension::<HdrThemeTokens>(), Some(&hdr_tokens));
901 assert_eq!(
902 Arc::as_ref(
903 &theme
904 .extension_arc::<HdrThemeTokens>()
905 .expect("hdr theme tokens extension present")
906 ),
907 &hdr_tokens
908 );
909 }
910
911 #[test]
912 fn theme_extensions_support_arc_access_and_removal() {
913 let mut theme = Theme::new();
914 theme.insert_extension(CustomWidgetTheme {
915 radius: 12.0,
916 density: 3,
917 });
918
919 let extension = theme
920 .extension_arc::<CustomWidgetTheme>()
921 .expect("custom widget theme present");
922 assert_eq!(
923 Arc::as_ref(&extension),
924 &CustomWidgetTheme {
925 radius: 12.0,
926 density: 3,
927 }
928 );
929
930 let removed = theme
931 .remove_extension::<CustomWidgetTheme>()
932 .expect("custom widget theme removed");
933 assert_eq!(
934 Arc::as_ref(&removed),
935 &CustomWidgetTheme {
936 radius: 12.0,
937 density: 3,
938 }
939 );
940 assert!(!theme.has_extension::<CustomWidgetTheme>());
941 }
942
943 #[test]
944 fn prelude_exports_rich_text_document_types() {
945 use crate::prelude::*;
946
947 let style = TextStyle::new(Color::WHITE);
948 let document = TextDocument {
949 paragraphs: vec![TextParagraph::from_spans(vec![TextSpan::new(
950 "Hello rich text",
951 style,
952 )])],
953 };
954 let _widget = RichText::new(document);
955 let _theme = DefaultTheme::default().with_density(ThemeDensity::Compact);
956 }
957
958 #[cfg(feature = "wgpu")]
959 #[test]
960 fn application_feather_width_is_configurable() {
961 let options = WindowRenderOptions::new(true, 1.5)
962 .with_color_management_mode(WindowColorManagementMode::PreferHdr)
963 .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
964 .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
965 .with_tone_mapping_mode(WindowToneMappingMode::Reinhard);
966 let app = Application::new()
967 .with_feathering_enabled(false)
968 .with_feather_width(2.25)
969 .with_window_render_options(options);
970 let clamped = Application::new().with_feather_width(-1.0);
971
972 assert!(!app.feathering_enabled());
973 assert_eq!(app.feather_width(), 2.25);
974 assert_eq!(clamped.feather_width(), 0.0);
975 assert_eq!(app.initial_window_render_options(), Some(options));
976 }
977
978 #[cfg(feature = "wgpu")]
979 #[test]
980 fn application_accepts_external_texture_registry() {
981 let registry = WgpuExternalTextureRegistry::new();
982 let app = Application::new().with_external_texture_registry(registry.clone());
983
984 assert!(app.external_texture_registry().is_some());
985 assert!(registry.context().is_none());
986 }
987}