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, BusyIndicator, CalloutPaint, CodePanelPaint,
41 CodeTextLine, CodeTextPaint, CodeTextSpan, CommandButtonFill, CommandButtonPaint, CommandGroup,
42 CommandPalette, ContextMenu, Dialog, DisclosureButtonPaint, DockPanel, Drawer, EmptyState,
43 EmptyStatePaint, FieldGroup, FormRow, FormSection, FramedField, HairlineEdge, Menu, MenuItem,
44 Modal, PanelSection, Popover, PopoverAlignment, PresetStrip, ProgressBar, PropertyRow,
45 PropertyRowLayout, SectionLabel, SectionLabelPaint, SectionPanelGeometry, SectionPanelPaint,
46 SheetState, SideSheet, SideSheetPlacement, Spinner, StatusBar, StatusBarHost, StatusBarSegment,
47 Surface, SurfaceAppearance, SurfaceBorder, SurfaceElevation, SurfaceRole, TabBar, Tabs,
48 ToolPalette, ToolPaletteItem, Toolbar, Tooltip, TooltipAlignment, TooltipPlacement,
49 paint_action_tile, paint_border, paint_callout, paint_code_lines, paint_code_panel,
50 paint_command_button, paint_disclosure_button, paint_empty_state, paint_hairline,
51 paint_placement_badge_with, paint_rounded_panel, paint_rounded_rect, paint_section_label,
52 paint_section_label_detail, paint_section_panel,
53};
54pub use containers::{
55 Align, Background, ContentExtent, Dock, FixedPaneSplit, Flex, MeasuredBottomDock, Overflow,
56 RebuildOnChange, RebuildOnConstraints, ScrollAxes, ScrollBar, ScrollState, ScrollView,
57 SemanticRegion, SizedBox, Stack, SwitchView, TrailingSlotRow, VirtualScrollView,
58};
59pub use controls::{
60 BUILTIN_ICON_GLYPHS, Button, ButtonAppearance, Checkbox, CheckboxIndicatorState,
61 ChoiceAppearance, ComboBox, DateTimeInput, Divider, FieldAppearance, Icon, IconButton,
62 IconButtonPaint, IconGlyph, Label, Link, MultilineTextInput, NumberInput, PasswordInput,
63 RadioButton, RadioGroup, Select, Separator, Slider, SpinBox, Switch, TextArea, TextInput,
64 draw_glyph, paint_checkbox_indicator, paint_icon_button, register_builtin_icon_resources,
65};
66pub use sui_core::{
67 AsyncWakeToken, Clipboard, ClipboardBackend, Color, ColorSpace, CustomEvent, DirtyRegion,
68 DpiInfo, DragDropScope, DragEvent, DragEventKind, DragOutcome, DragPayload, DragPreview,
69 DragScopeId, DragSessionId, DropEffect, Error, Event, FontHandle, ImageHandle, ImeEvent,
70 InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState, KeyboardEvent,
71 LocalClipboardBackend, Modifiers, Path, PathBuilder, PathElement, Point, PointerButton,
72 PointerButtons, PointerEvent, PointerEventKind, PointerKind, Rect, Result, SafeAreaInsets,
73 ScrollDelta, SemanticsAction, SemanticsActionRequest, SemanticsEvent, SemanticsLiveRegion,
74 SemanticsNode, SemanticsPopupKind, SemanticsRelations, SemanticsRole, SemanticsState,
75 SemanticsTextRange, SemanticsValue, Size, SurfaceId, TimerToken, ToggleState, Transform,
76 Vector, WakeEvent, WidgetId, WindowEvent, WindowId,
77};
78pub use sui_layout::Padding as Insets;
79pub use sui_layout::{
80 Alignment, Axis, Constraints, FlexAlignContent, FlexBasis, FlexItem, FlexItemLayout,
81 FlexJustify, FlexLayout, FlexLineLayout, FlexStyle, FlexWrap, GridItem, GridItemLayout,
82 GridLayout, GridPlacement, GridStyle, GridTrack, GridTrackMax, IntrinsicSize, LayoutContext,
83 Padding, arrange_flex, flex_layout, grid_layout,
84};
85#[cfg(all(target_os = "android", feature = "mobile"))]
86pub use sui_platform::AndroidApp;
87#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
88pub use sui_platform::{
89 AccessibilityIssue, AccessibilityIssueSeverity, AccessibilityIssueTarget,
90 AccessibilitySnapshot, DesktopAutomationAction, DesktopAutomationConfig, DesktopPlatform,
91 FileDialogFilter, FileDialogFuture, FileDialogMode, FileDialogRequest, FileDialogSelection,
92 FileDialogService, HeadlessPlatform, NativeFileDialogs, PlatformFile, PlatformWindow, Waker,
93 WindowOutputDiagnostics, show_file_dialog, validate_accessibility_snapshot,
94 window_output_diagnostics,
95};
96pub use sui_reactive::{
97 Change as ObservableChange, Observable, Observer, Selector, Signal, SourceId, Subscription,
98 WeakObserver,
99};
100#[cfg(feature = "wgpu")]
101pub use sui_render_wgpu::{
102 RendererCapabilities, RendererInterop, StemDarkening, TextCoveragePolicy, TextHinting,
103 WgpuExternalTextureContext, WgpuExternalTextureRegistry, WgpuRenderer,
104};
105pub use sui_runtime::{
106 Application as RuntimeApplication, ArrangeCtx, AsyncTaskInspectorSnapshot, CacheMetrics,
107 CacheMetricsDelta, Command, CommandController, CommandCtx, CommandDelivery,
108 CommandDispatchSample, CommandKey, CommandSender, CommandTarget, DEFAULT_SUI_LOGO_SVG,
109 EXTERNAL_WAKE_KIND, EmbeddedSvgImageResource, EventCtx, EventPhase, EventRoutePhase,
110 EventRouteStep, EventRouteTraceSample, FocusRestorePolicy, FocusScope, FocusScopeState,
111 FocusState, FramePhase, FramePhaseSample, FrameSchedule, InspectorHistorySnapshot,
112 InvalidationTraceSample, KeyedChildren, KeyedReconcile, MeasureCtx, OVERLAY_DISMISS_REQUEST,
113 OverlayDismissPolicy, OverlayDismissReason, OverlayDismissRequest, OverlayFocusBehavior,
114 OverlayInitialFocus, OverlayKind, OverlayManagerSnapshot, OverlayModality, OverlayOptions,
115 OverlaySnapshot, OverlayTraceKind, OverlayTraceSample, PaintCtx,
116 PresentationLatencyDiagnostics, REACTIVE_CHANGED, ReactiveInvalidationSample,
117 RenderDiagnostics, RenderOutput, RendererSubmissionDiagnostics,
118 RetainedPacketRebuildDiagnostics, Runtime, SceneStatistics, SceneStatisticsDetailMode,
119 SchedulerInspectorSnapshot, SemanticsCtx, SingleChild, StackHostOptions, StackOrderPolicy,
120 StackSurfaceOptions, TextCacheDeltaDiagnostics, TextCacheDiagnostics, TimerInspectorSnapshot,
121 Widget, WidgetChildren, WidgetDiagnostic, WidgetDiagnosticsCtx, WidgetDiagnosticsSnapshot,
122 WidgetGeometrySnapshot, WidgetGraphSnapshot, WidgetNodeSnapshot, WidgetPod,
123 WidgetPodMutVisitor, WidgetPodVisitor, WidgetRebuildSample, WindowBuilder,
124 WindowColorManagementMode, WindowDynamicRangeMode, WindowIcon, WindowInspectorSnapshot,
125 WindowOutputColorPrimaries, WindowPerformanceSnapshot, WindowPerformanceSummary,
126 WindowRenderOptions, WindowStemDarkening, WindowTextCoveragePolicy, WindowTextHinting,
127 WindowTextSubpixelOrder, WindowToneMappingMode, clear_window_render_options,
128 default_sui_logo_image, set_window_render_options, set_window_scene_statistics_detail_mode,
129 window_performance_snapshot, window_performance_summary, window_render_options,
130 window_scene_statistics_detail_mode,
131};
132pub use sui_scene::{
133 Border, Brush, GradientStop, ImageRegistry, ImageSource, RegisteredExternalImage,
134 RegisteredImage, RegisteredImageFormat, Scene, SceneCommand, SceneFrame, ShadowParams,
135 StrokeStyle, TextRenderCoveragePolicy, TextRenderHinting, TextRenderMode, TextRenderPolicy,
136 TextRenderStemDarkening, TextSubpixelOrder, WidgetShader,
137};
138pub use sui_text::{
139 FontFamilyStack, FontFeature, FontFeatures, FontRegistry, FontStretch, FontStyle, FontWeight,
140 PersistentTextLayout, RegisteredFont, ResolvedTextFace, ShapedGlyph, ShapedText,
141 ShapedTextWindow, TextAffinity, TextAlign, TextCluster, TextCursor, TextDirection,
142 TextDocument, TextFlowDirection, TextGlyphInstance, TextLayout, TextLayoutHandle, TextLayoutId,
143 TextLayoutMetadata, TextLayoutRegistry, TextLayoutRequest, TextLayoutRun, TextLayoutVersion,
144 TextLayoutView, TextLine, TextLineWindow, TextMeasurement, TextParagraph, TextParagraphLayout,
145 TextParagraphStyle, TextRun, TextRunView, TextSelection, TextSelectionGeometry, TextSpan,
146 TextSpanId, TextStyle, TextWrap, TextWritingMode,
147};
148pub use sui_widgets::SignalMeter;
149pub use sui_widgets::animation::{
150 ANIMATION_DOCUMENT_VERSION, AnimatedValue, AnimationBinding, AnimationBindingInvalidation,
151 AnimationDocument, AnimationDocumentFormatError, AnimationEditorCommand, AnimationEditorState,
152 AnimationPlayer, AnimationProperty, AnimationPropertyPath, AnimationSelection,
153 AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind, Blink, Clip,
154 CompiledClip, CompiledTimeline, CompiledTrack, Easing, Interpolate, Keyframe,
155 KeyframeSelection, LoopMode, PlaybackState, Pulse, SampleBatch, SampleBuffer,
156 SampledAnimationValue, SharedCompiledTimeline, SpringF32, Timeline, TimelineBindingSink,
157 TimelinePlayer, TimelineSnap, TimelineTick, Track, Transition,
158 invalidation_for_animation_property,
159};
160pub use sui_widgets::{
161 ActionCard, AdaptiveBreakpoints, AdaptiveClass, AdaptiveView, AspectRatio, AspectRatioFit,
162 BasicSyntaxHighlighter, Breadcrumb, BreadcrumbItem, BrushPreview, BrushPreviewShape,
163 BrushPreviewSpec, Canvas, CanvasRuler, CanvasRulerAxis, CanvasShape, CanvasStroke,
164 CanvasViewport, CollectionAnchor, CollectionAnchorGravity, CollectionChange, CollectionDelta,
165 CollectionExtentIndex, CollectionModelError, CollectionSync, CollectionWindow, ColorPalette,
166 ColorPaletteSwatch, ColorPicker, ColorSwatch, ConstraintOrientation, ConstraintQuery,
167 ConstraintView, ControlMetrics, ControlPalette, ControlSize, ControlTypography, CoverageDots,
168 CoverageDotsConfig, DataGrid, DefaultTheme, DetailRow, DragDropHost, Draggable, DropTarget,
169 EffectToken, FloatingStack, FloatingViewConfig, FloatingViewSnapshot, FloatingWorkspace,
170 FloatingWorkspaceState, Grid, GridCell, HdrColorRoles, HdrEffectTokens, HdrLuminanceTokens,
171 HdrMaterialTokens, HdrPolicyTokens, HdrThemeMode, HdrThemeTokens, Image, ImageFit, LayerList,
172 LayerListItem, LayerListReorderChange, LayoutTransition, LeadingLabelCellPaint, ListItem,
173 ListView, MasterDetail, MasterDetailRoute, MasterDetailState, MaterialToken,
174 NotificationCenter, NotificationHost, NotificationId, NotificationUrgency, OverlayAlignment,
175 OverlayCollisionPolicy, OverlayHost, OverlayPlacement, OverlayPlacementRequest,
176 OverlayPlacementResult, OverlaySide, PathBar, PixelCanvas, PixelCanvasBlendMode,
177 PixelCanvasBrushShape, PixelCanvasExportSnapshot, PixelCanvasState, PixelCanvasTool,
178 PlacementBadge, PlacementBadgePaint, ReorderableList, ReorderableListChange, ResizablePane,
179 ResolvedEffectStyle, ResolvedHdrStyle, ResolvedMaterialStyle, ResponsiveSidebar,
180 ResponsiveSidebarMode, ResponsiveSidebarSnapshot, ResponsiveSidebarState, RichAttachment,
181 RichBlockId, RichDocumentBlock, RichDocumentBlockKind, RichDocumentModel,
182 RichDocumentRenderContext, RichDocumentRendererRegistry, RichDocumentSnapshot,
183 RichDocumentSpan, RichDocumentStatus, RichDocumentUpdate, RichDocumentView,
184 RichDocumentViewState, RichExtensionBlock, RichInlineImage, RichInlineKind, RichInlineStyle,
185 RichLink, RichListItem, RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind, RichText,
186 RichTextSourceMap, RichTextSourceSpan, SafeArea, SafeAreaEdges, ScrollAlignment,
187 SegmentedControl, SegmentedControlItem, SelectionChange, SelectionEntry, SelectionIntent,
188 SelectionOrder, SelectionOwnerId, SelectionPayload, SelectionPoint, SelectionScope,
189 SemanticColorToken, SemanticTone, SplitExtent, SplitPaneSide, SplitState, SplitStateSnapshot,
190 SplitView, StatusBadge, SurfacePalette, TEXT_COMMAND, Table, TableColumn, TableColumnAlignment,
191 TableRow, TextBlockPaint, TextCellPaint, TextCommand, TextSelectionInfo, TextSurface,
192 TextSurfaceOverlayKind, TextSurfaceStyleOverlay, TextSurfaceStyleSpan, ThemeAspectRatios,
193 ThemeBlurScale, ThemeBreakpoints, ThemeColorScheme, ThemeColors, ThemeContainers, ThemeDensity,
194 ThemeFontFamilies, ThemeFontStack, ThemeFontWeights, ThemeLeading, ThemeMotion,
195 ThemePerspective, ThemeRadii, ThemeShadow, ThemeShadowLayer, ThemeShadows, ThemeTextScale,
196 ThemeTextToken, ThemeTracking, TransientNotification, TreeItem, TreeView,
197 VirtualCollectionModel, VirtualCollectionSource, VirtualList, VirtualListChrome,
198 VirtualListSelectionMode, VirtualListState, VirtualTable, VirtualTableColumn,
199 VirtualTableRowActivationKind, VirtualTableRowContext, VirtualTableSortDirection,
200 VirtualTableState, VirtualViewportSnapshot, WidgetColorRole, WidgetEffectRole,
201 WidgetLuminanceRole, WidgetMaterialRole, detail_row_height_for_value, paint_aligned_text,
202 paint_coverage_dots, paint_coverage_dots_with_config, paint_detail_row_at,
203 paint_leading_label_cell, paint_placement_badge, paint_progress_bar,
204 paint_single_line_aligned_text, paint_status_badge, paint_text_block, paint_text_cell,
205 paint_theme_shadow, place_overlay, resolve_effect_role, resolve_luminance_role,
206 resolve_material_role, resolve_semantic_color, resolve_widget_hdr_style, wrap_text_lines,
207};
208
209pub trait ThemeExtension: Any + Send + Sync {}
211
212impl<T> ThemeExtension for T where T: Any + Send + Sync {}
213
214#[derive(Clone, Default)]
216pub struct ThemeExtensions {
217 values: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
218}
219
220impl ThemeExtensions {
221 pub fn new() -> Self {
223 Self::default()
224 }
225
226 pub fn insert<T>(&mut self, value: T) -> Option<Arc<T>>
228 where
229 T: ThemeExtension,
230 {
231 self.values
232 .insert(TypeId::of::<T>(), Arc::new(value))
233 .and_then(|previous| Arc::downcast::<T>(previous).ok())
234 }
235
236 pub fn get<T>(&self) -> Option<&T>
238 where
239 T: ThemeExtension,
240 {
241 self.values
242 .get(&TypeId::of::<T>())
243 .and_then(|value| value.as_ref().downcast_ref::<T>())
244 }
245
246 pub fn get_arc<T>(&self) -> Option<Arc<T>>
248 where
249 T: ThemeExtension,
250 {
251 self.values
252 .get(&TypeId::of::<T>())
253 .and_then(|value| Arc::clone(value).downcast::<T>().ok())
254 }
255
256 pub fn contains<T>(&self) -> bool
258 where
259 T: ThemeExtension,
260 {
261 self.values.contains_key(&TypeId::of::<T>())
262 }
263
264 pub fn remove<T>(&mut self) -> Option<Arc<T>>
266 where
267 T: ThemeExtension,
268 {
269 self.values
270 .remove(&TypeId::of::<T>())
271 .and_then(|value| Arc::downcast::<T>(value).ok())
272 }
273
274 pub fn is_empty(&self) -> bool {
276 self.values.is_empty()
277 }
278
279 pub fn len(&self) -> usize {
281 self.values.len()
282 }
283}
284
285impl fmt::Debug for ThemeExtensions {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 f.debug_struct("ThemeExtensions")
288 .field("len", &self.values.len())
289 .finish()
290 }
291}
292
293#[derive(Debug, Clone)]
295pub struct Theme {
296 pub background: Color,
298 pub foreground: Color,
300 pub default_widgets: DefaultTheme,
302 pub extensions: ThemeExtensions,
304}
305
306impl Default for Theme {
307 fn default() -> Self {
308 let default_widgets = DefaultTheme::default();
309 Self {
310 background: default_widgets.palette.surface,
311 foreground: default_widgets.palette.text,
312 default_widgets,
313 extensions: ThemeExtensions::default(),
314 }
315 }
316}
317
318impl Theme {
319 pub fn new() -> Self {
321 Self::default()
322 }
323
324 pub fn with_default_widgets(mut self, theme: DefaultTheme) -> Self {
326 self.default_widgets = theme;
327 self
328 }
329
330 pub fn with_extension<T>(mut self, value: T) -> Self
332 where
333 T: ThemeExtension,
334 {
335 self.extensions.insert(value);
336 self
337 }
338
339 pub fn insert_extension<T>(&mut self, value: T) -> Option<Arc<T>>
341 where
342 T: ThemeExtension,
343 {
344 self.extensions.insert(value)
345 }
346
347 pub fn extension<T>(&self) -> Option<&T>
349 where
350 T: ThemeExtension,
351 {
352 self.extensions.get::<T>()
353 }
354
355 pub fn extension_arc<T>(&self) -> Option<Arc<T>>
357 where
358 T: ThemeExtension,
359 {
360 self.extensions.get_arc::<T>()
361 }
362
363 pub fn has_extension<T>(&self) -> bool
365 where
366 T: ThemeExtension,
367 {
368 self.extensions.contains::<T>()
369 }
370
371 pub fn remove_extension<T>(&mut self) -> Option<Arc<T>>
373 where
374 T: ThemeExtension,
375 {
376 self.extensions.remove::<T>()
377 }
378}
379
380pub struct Application {
385 inner: RuntimeApplication,
386 #[cfg(feature = "wgpu")]
387 feathering_enabled: bool,
388 #[cfg(feature = "wgpu")]
389 feather_width: f32,
390 #[cfg(feature = "wgpu")]
391 external_texture_registry: Option<WgpuExternalTextureRegistry>,
392 initial_window_render_options: Option<WindowRenderOptions>,
393}
394
395impl Default for Application {
396 fn default() -> Self {
397 let mut inner = RuntimeApplication::default();
398 sui_widgets::register_builtin_icon_resources(&mut inner)
399 .expect("built-in Lucide icon resources should be valid");
400 Self {
401 inner,
402 #[cfg(feature = "wgpu")]
403 feathering_enabled: WgpuRenderer::new().feathering_enabled(),
404 #[cfg(feature = "wgpu")]
405 feather_width: WgpuRenderer::new().feather_width(),
406 #[cfg(feature = "wgpu")]
407 external_texture_registry: None,
408 initial_window_render_options: None,
409 }
410 }
411}
412
413impl Application {
414 pub fn new() -> Self {
416 Self::default()
417 }
418
419 pub fn window(mut self, window: WindowBuilder) -> Self {
421 self.inner = self.inner.window(window);
422 self
423 }
424
425 pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
427 self.inner = self.inner.controller(controller);
428 self
429 }
430
431 pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
433 where
434 T: Send + Sync + 'static,
435 F: FnMut(&mut CommandCtx, &T) + 'static,
436 {
437 self.inner = self.inner.on_command(key, handler);
438 self
439 }
440
441 #[cfg(feature = "wgpu")]
442 pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
444 self.feathering_enabled = enabled;
445 self
446 }
447
448 #[cfg(feature = "wgpu")]
449 pub fn with_feather_width(mut self, feather_width: f32) -> Self {
451 self.feather_width = feather_width.max(0.0);
452 self
453 }
454
455 #[cfg(feature = "wgpu")]
456 pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
458 self.external_texture_registry = Some(registry);
459 self
460 }
461
462 #[cfg(feature = "wgpu")]
463 pub fn feathering_enabled(&self) -> bool {
465 self.feathering_enabled
466 }
467
468 #[cfg(feature = "wgpu")]
469 pub fn feather_width(&self) -> f32 {
471 self.feather_width
472 }
473
474 #[cfg(feature = "wgpu")]
475 pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
477 self.external_texture_registry.as_ref()
478 }
479
480 pub fn with_window_render_options(mut self, options: WindowRenderOptions) -> Self {
482 self.initial_window_render_options = Some(options.clamped());
483 self
484 }
485
486 pub fn initial_window_render_options(&self) -> Option<WindowRenderOptions> {
488 self.initial_window_render_options
489 }
490
491 pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
493 self.inner.register_font(handle, font)
494 }
495
496 pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
498 self.inner.register_font_bytes(data)
499 }
500
501 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
503 self.inner.register_image(handle, image)
504 }
505
506 pub fn register_rgba_image(
508 &mut self,
509 width: u32,
510 height: u32,
511 data: impl Into<Vec<u8>>,
512 ) -> Result<ImageHandle> {
513 self.inner.register_rgba_image(width, height, data)
514 }
515
516 pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
518 self.inner.register_svg_image(data)
519 }
520
521 pub fn register_svg_image_with_handle(
523 &mut self,
524 handle: ImageHandle,
525 data: impl AsRef<[u8]>,
526 ) -> Result<()> {
527 self.inner.register_svg_image_with_handle(handle, data)
528 }
529
530 pub fn register_svg_image_at_size(
532 &mut self,
533 width: u32,
534 height: u32,
535 data: impl AsRef<[u8]>,
536 ) -> Result<ImageHandle> {
537 self.inner.register_svg_image_at_size(width, height, data)
538 }
539
540 pub fn register_svg_image_at_size_with_handle(
542 &mut self,
543 handle: ImageHandle,
544 width: u32,
545 height: u32,
546 data: impl AsRef<[u8]>,
547 ) -> Result<()> {
548 self.inner
549 .register_svg_image_at_size_with_handle(handle, width, height, data)
550 }
551
552 pub fn register_embedded_svg_image(
554 &mut self,
555 resource: EmbeddedSvgImageResource,
556 ) -> Result<()> {
557 self.inner.register_embedded_svg_image(resource)
558 }
559
560 pub fn register_embedded_svg_images(
562 &mut self,
563 resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
564 ) -> Result<()> {
565 self.inner.register_embedded_svg_images(resources)
566 }
567
568 pub fn build(self) -> Result<Runtime> {
570 self.inner.build()
571 }
572
573 #[cfg(any(feature = "desktop", feature = "web"))]
574 pub fn run(self) -> Result<()> {
576 let feathering_enabled = self.feathering_enabled;
577 let feather_width = self.feather_width;
578 let external_texture_registry = self.external_texture_registry.clone();
579 let initial_window_render_options = self.initial_window_render_options;
580 let runtime = self.build()?;
581 let mut platform = DesktopPlatform::new()
582 .with_feathering_enabled(feathering_enabled)
583 .with_feather_width(feather_width);
584 if let Some(registry) = external_texture_registry {
585 platform.set_external_texture_registry(registry);
586 }
587 if let Some(options) = initial_window_render_options {
588 for window_id in runtime.window_ids() {
589 set_window_render_options(window_id, options);
590 }
591 }
592 let _ = platform.run(runtime)?;
593 Ok(())
594 }
595
596 #[cfg(any(feature = "desktop", feature = "web"))]
599 pub fn run_with(self, on_ready: impl FnOnce(CommandSender)) -> Result<()> {
600 let feathering_enabled = self.feathering_enabled;
601 let feather_width = self.feather_width;
602 let external_texture_registry = self.external_texture_registry.clone();
603 let initial_window_render_options = self.initial_window_render_options;
604 let runtime = self.build()?;
605 let mut platform = DesktopPlatform::new()
606 .with_feathering_enabled(feathering_enabled)
607 .with_feather_width(feather_width);
608 if let Some(registry) = external_texture_registry {
609 platform.set_external_texture_registry(registry);
610 }
611 if let Some(options) = initial_window_render_options {
612 for window_id in runtime.window_ids() {
613 set_window_render_options(window_id, options);
614 }
615 }
616 let _ = platform.run_with(runtime, on_ready)?;
617 Ok(())
618 }
619
620 #[cfg(all(target_os = "android", feature = "mobile"))]
621 pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
623 self.run_android_with(android_app, |_| {})
624 }
625
626 #[cfg(all(target_os = "android", feature = "mobile"))]
627 pub fn run_android_with(
629 self,
630 android_app: AndroidApp,
631 on_ready: impl FnOnce(CommandSender),
632 ) -> Result<()> {
633 let feathering_enabled = self.feathering_enabled;
634 let feather_width = self.feather_width;
635 let external_texture_registry = self.external_texture_registry.clone();
636 let initial_window_render_options = self.initial_window_render_options;
637 let runtime = self.build()?;
638 let mut platform = DesktopPlatform::new()
639 .with_feathering_enabled(feathering_enabled)
640 .with_feather_width(feather_width);
641 if let Some(registry) = external_texture_registry {
642 platform.set_external_texture_registry(registry);
643 }
644 if let Some(options) = initial_window_render_options {
645 for window_id in runtime.window_ids() {
646 set_window_render_options(window_id, options);
647 }
648 }
649 let _ = platform.run_android_with(runtime, android_app, on_ready)?;
650 Ok(())
651 }
652
653 #[cfg(not(any(feature = "desktop", feature = "web", feature = "mobile")))]
654 pub fn run(self) -> Result<()> {
656 let _ = self;
657 Err(Error::new(
658 "Application::run requires the `desktop`, `web`, or `mobile` feature to provide a platform event loop",
659 ))
660 }
661}
662
663#[derive(Debug, Clone, PartialEq)]
665pub struct Style {
666 pub foreground: Brush,
668 pub padding: Padding,
670}
671
672impl Default for Style {
673 fn default() -> Self {
674 let theme = Theme::default();
675
676 Self {
677 foreground: Brush::Solid(theme.foreground),
678 padding: Padding::all(0.0),
679 }
680 }
681}
682
683pub mod prelude {
685 #[cfg(any(feature = "desktop", feature = "web"))]
686 pub use crate::UiHandle;
687 #[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
688 pub use crate::{
689 FileDialogFilter, FileDialogMode, FileDialogRequest, FileDialogSelection,
690 FileDialogService, NativeFileDialogs, PlatformFile, show_file_dialog,
691 };
692
693 pub use crate::{
694 ActionCard, ActionTilePaint, AdaptiveBreakpoints, AdaptiveClass, AdaptiveView, Align,
695 Alignment, AnimatedValue, AnimationBinding, AnimationDocument,
696 AnimationDocumentFormatError, AnimationEditorCommand, AnimationEditorState,
697 AnimationPlayer, AnimationProperty, AnimationPropertyPath, AnimationSelection,
698 AnimationTargetId, AnimationTick, AnimationValue, AnimationValueKind, App, Application,
699 ArrangeCtx, AspectRatio, AspectRatioFit, AsyncWakeToken, Axis, Background,
700 BasicSyntaxHighlighter, Blink, BottomSheet, Breadcrumb, BreadcrumbItem, BrowserTabBar,
701 Brush, BrushPreview, BrushPreviewShape, BrushPreviewSpec, BusyIndicator, Button,
702 ButtonAppearance, CalloutPaint, Canvas, CanvasRuler, CanvasRulerAxis, CanvasShape,
703 CanvasStroke, CanvasViewport, Checkbox, CheckboxIndicatorState, ChoiceAppearance, Clip,
704 CodePanelPaint, CodeTextLine, CodeTextPaint, CodeTextSpan, CollectionAnchor,
705 CollectionAnchorGravity, CollectionChange, CollectionDelta, CollectionExtentIndex,
706 CollectionModelError, CollectionSync, CollectionWindow, Color, ColorPalette,
707 ColorPaletteSwatch, ColorPicker, ColorSwatch, ComboBox, Command, CommandButtonFill,
708 CommandButtonPaint, CommandController, CommandCtx, CommandDelivery, CommandGroup,
709 CommandKey, CommandPalette, CommandSender, CommandTarget, CompiledClip, CompiledTimeline,
710 CompiledTrack, ConstraintOrientation, ConstraintQuery, ConstraintView, Constraints,
711 ContentExtent, ContextMenu, ControlMetrics, ControlPalette, ControlSize, ControlTypography,
712 CoverageDots, CoverageDotsConfig, DataGrid, DateTimeInput, DefaultTheme, DetailRow, Dialog,
713 DisclosureButtonPaint, Divider, Dock, DockPanel, DragDropHost, DragDropScope, DragEvent,
714 DragEventKind, DragOutcome, DragPayload, DragPreview, DragScopeId, DragSessionId,
715 Draggable, Drawer, DropEffect, DropTarget, Easing, EmptyState, EmptyStatePaint, Event,
716 EventCtx, FieldAppearance, FieldGroup, FixedPaneSplit, Flex, FlexAlignContent, FlexBasis,
717 FlexItem, FlexItemLayout, FlexJustify, FlexLayout, FlexLineLayout, FlexStyle, FlexWrap,
718 FloatingViewConfig, FloatingViewSnapshot, FloatingWorkspace, FloatingWorkspaceState,
719 FocusRestorePolicy, FocusScope, FocusScopeState, FontFeature, FontFeatures, FontHandle,
720 FontStretch, FontStyle, FontWeight, FormRow, FormSection, FramedField, Grid, GridCell,
721 GridItem, GridItemLayout, GridLayout, GridPlacement, GridStyle, GridTrack, GridTrackMax,
722 HairlineEdge, Icon, IconButton, IconButtonPaint, IconGlyph, Image, ImageFit, ImageHandle,
723 ImeEvent, Insets, Interpolate, IntrinsicSize, KeyboardEvent, KeyedChildren, KeyedReconcile,
724 Keyframe, KeyframeSelection, Label, LayerList, LayerListItem, LayerListReorderChange,
725 LayoutTransition, LeadingLabelCellPaint, Link, ListItem, ListView, LoopMode, MasterDetail,
726 MasterDetailRoute, MasterDetailState, MeasureCtx, MeasuredBottomDock, Menu, MenuItem,
727 Modal, MultilineTextInput, NotificationCenter, NotificationHost, NotificationId,
728 NotificationUrgency, NumberInput, Observable, Overflow, OverlayAlignment,
729 OverlayCollisionPolicy, OverlayDismissPolicy, OverlayDismissReason, OverlayFocusBehavior,
730 OverlayHost, OverlayKind, OverlayOptions, OverlayPlacement, OverlayPlacementRequest,
731 OverlayPlacementResult, OverlaySide, PaintCtx, PanelSection, PasswordInput, Path, PathBar,
732 PathBuilder, PixelCanvas, PixelCanvasBlendMode, PixelCanvasBrushShape,
733 PixelCanvasExportSnapshot, PixelCanvasState, PixelCanvasTool, PlacementBadgePaint,
734 PlaybackState, Point, PointerEvent, Popover, PresetStrip, ProgressBar, PropertyRow,
735 PropertyRowLayout, Pulse, RadioButton, RadioGroup, RebuildOnChange, RebuildOnConstraints,
736 Rect, RegisteredFont, RegisteredImage, ReorderableList, ReorderableListChange,
737 ResizablePane, ResourceRegistry, ResponsiveSidebar, ResponsiveSidebarMode,
738 ResponsiveSidebarSnapshot, ResponsiveSidebarState, Result, RichAttachment, RichBlockId,
739 RichDocumentBlock, RichDocumentBlockKind, RichDocumentModel, RichDocumentRenderContext,
740 RichDocumentRendererRegistry, RichDocumentSnapshot, RichDocumentSpan, RichDocumentStatus,
741 RichDocumentUpdate, RichDocumentView, RichDocumentViewState, RichExtensionBlock,
742 RichInlineImage, RichInlineKind, RichInlineStyle, RichLink, RichListItem,
743 RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind, RichText, RichTextSourceMap,
744 RichTextSourceSpan, SafeArea, SafeAreaEdges, SafeAreaInsets, SampleBatch, SampleBuffer,
745 SampledAnimationValue, ScrollAlignment, ScrollAxes, ScrollBar, ScrollState, ScrollView,
746 SectionLabel, SectionLabelPaint, SectionPanelGeometry, SectionPanelPaint, SegmentedControl,
747 SegmentedControlItem, Select, SelectionChange, SelectionEntry, SelectionIntent,
748 SelectionOrder, SelectionOwnerId, SelectionPayload, SelectionPoint, SelectionScope,
749 Selector, SemanticsCtx, Separator, ShapedText, SharedCompiledTimeline, SheetState,
750 SideSheet, SideSheetPlacement, Signal, SingleChild, Size, SizedBox, Slider, SourceId,
751 SpinBox, Spinner, SplitExtent, SplitPaneSide, SplitState, SplitStateSnapshot, SplitView,
752 SpringF32, Stack, StatusBar, StatusBarHost, StatusBarSegment, StrokeStyle, Style, Surface,
753 SurfaceAppearance, SurfaceBorder, SurfaceElevation, SurfacePalette, SurfaceRole, Switch,
754 SwitchView, TEXT_COMMAND, TabBar, Table, TableColumn, TableColumnAlignment, TableRow, Tabs,
755 TextArea, TextBlockPaint, TextCellPaint, TextCommand, TextDocument, TextInput, TextLayout,
756 TextMeasurement, TextParagraph, TextParagraphStyle, TextRenderCoveragePolicy,
757 TextRenderHinting, TextRenderMode, TextRenderPolicy, TextRenderStemDarkening,
758 TextSelectionInfo, TextSpan, TextSpanId, TextStyle, TextSubpixelOrder, TextWrap, Theme,
759 ThemeAspectRatios, ThemeBlurScale, ThemeBreakpoints, ThemeColorScheme, ThemeColors,
760 ThemeContainers, ThemeDensity, ThemeExtension, ThemeExtensions, ThemeFontFamilies,
761 ThemeFontStack, ThemeFontWeights, ThemeLeading, ThemeMotion, ThemePerspective, ThemeRadii,
762 ThemeShadow, ThemeShadowLayer, ThemeShadows, ThemeTextScale, ThemeTextToken, ThemeTracking,
763 Timeline, TimelineBindingSink, TimelinePlayer, TimelineSnap, TimelineTick, TimerToken,
764 ToolPalette, ToolPaletteItem, Toolbar, Tooltip, TooltipAlignment, TooltipPlacement, Track,
765 TrailingSlotRow, Transform, TransientNotification, Transition, TreeItem, TreeView,
766 VirtualCollectionModel, VirtualCollectionSource, VirtualList, VirtualListChrome,
767 VirtualListSelectionMode, VirtualListState, VirtualScrollView, VirtualTable,
768 VirtualTableColumn, VirtualTableRowActivationKind, VirtualTableRowContext,
769 VirtualTableSortDirection, VirtualTableState, VirtualViewportSnapshot, WakeEvent, Widget,
770 WidgetChildren, WidgetDiagnosticsCtx, WidgetPod, WidgetShader, Window, WindowBuilder,
771 WindowRenderOptions, arrange_flex, containers::Padding, detail_row_height_for_value,
772 flex_layout, grid_layout, invalidation_for_animation_property, paint_action_tile,
773 paint_border, paint_callout, paint_checkbox_indicator, paint_code_lines, paint_code_panel,
774 paint_command_button, paint_coverage_dots, paint_coverage_dots_with_config,
775 paint_detail_row_at, paint_disclosure_button, paint_empty_state, paint_hairline,
776 paint_icon_button, paint_leading_label_cell, paint_placement_badge_with,
777 paint_rounded_panel, paint_rounded_rect, paint_section_label, paint_section_label_detail,
778 paint_section_panel, paint_text_block, paint_text_cell, place_overlay,
779 register_builtin_icon_resources, set_window_render_options, wrap_text_lines,
780 };
781}
782
783#[cfg(test)]
784mod tests {
785 use std::sync::Arc;
786
787 use super::{DefaultTheme, HdrThemeMode, HdrThemeTokens, Theme};
788 #[cfg(feature = "wgpu")]
789 use crate::{
790 Application, WgpuExternalTextureRegistry, WindowColorManagementMode,
791 WindowDynamicRangeMode, WindowOutputColorPrimaries, WindowRenderOptions,
792 WindowToneMappingMode,
793 };
794
795 #[derive(Debug, PartialEq)]
796 struct CustomWidgetTheme {
797 radius: f32,
798 density: u8,
799 }
800
801 #[test]
802 fn theme_stores_default_widget_theme_separately_from_extensions() {
803 let mut defaults = DefaultTheme::default();
804 defaults.metrics.min_height = 24.0;
805
806 let theme = Theme::new()
807 .with_default_widgets(defaults)
808 .with_extension(CustomWidgetTheme {
809 radius: 6.0,
810 density: 2,
811 });
812
813 assert_eq!(theme.default_widgets.metrics.min_height, 24.0);
814 assert!(theme.has_extension::<CustomWidgetTheme>());
815 assert_eq!(
816 theme.extension::<CustomWidgetTheme>(),
817 Some(&CustomWidgetTheme {
818 radius: 6.0,
819 density: 2,
820 })
821 );
822 }
823
824 #[test]
825 fn theme_extensions_round_trip_hdr_theme_tokens() {
826 let mut defaults = DefaultTheme::dark();
827 defaults.metrics.min_height = 30.0;
828 defaults.hdr.mode = HdrThemeMode::WideGamutOnly;
829
830 let hdr_tokens = HdrThemeTokens {
831 mode: HdrThemeMode::FullHdr,
832 ..HdrThemeTokens::default()
833 };
834
835 let theme = Theme::new()
836 .with_default_widgets(defaults)
837 .with_extension(hdr_tokens);
838
839 assert_eq!(theme.default_widgets.metrics.min_height, 30.0);
840 assert_eq!(theme.default_widgets.hdr.mode, HdrThemeMode::WideGamutOnly);
841 assert!(theme.has_extension::<HdrThemeTokens>());
842 assert_eq!(theme.extension::<HdrThemeTokens>(), Some(&hdr_tokens));
843 assert_eq!(
844 Arc::as_ref(
845 &theme
846 .extension_arc::<HdrThemeTokens>()
847 .expect("hdr theme tokens extension present")
848 ),
849 &hdr_tokens
850 );
851 }
852
853 #[test]
854 fn theme_extensions_support_arc_access_and_removal() {
855 let mut theme = Theme::new();
856 theme.insert_extension(CustomWidgetTheme {
857 radius: 12.0,
858 density: 3,
859 });
860
861 let extension = theme
862 .extension_arc::<CustomWidgetTheme>()
863 .expect("custom widget theme present");
864 assert_eq!(
865 Arc::as_ref(&extension),
866 &CustomWidgetTheme {
867 radius: 12.0,
868 density: 3,
869 }
870 );
871
872 let removed = theme
873 .remove_extension::<CustomWidgetTheme>()
874 .expect("custom widget theme removed");
875 assert_eq!(
876 Arc::as_ref(&removed),
877 &CustomWidgetTheme {
878 radius: 12.0,
879 density: 3,
880 }
881 );
882 assert!(!theme.has_extension::<CustomWidgetTheme>());
883 }
884
885 #[test]
886 fn prelude_exports_rich_text_document_types() {
887 use crate::prelude::*;
888
889 let style = TextStyle::new(Color::WHITE);
890 let document = TextDocument {
891 paragraphs: vec![TextParagraph::from_spans(vec![TextSpan::new(
892 "Hello rich text",
893 style,
894 )])],
895 };
896 let _widget = RichText::new(document);
897 let _theme = DefaultTheme::default().with_density(ThemeDensity::Compact);
898 }
899
900 #[cfg(feature = "wgpu")]
901 #[test]
902 fn application_feather_width_is_configurable() {
903 let options = WindowRenderOptions::new(true, 1.5)
904 .with_color_management_mode(WindowColorManagementMode::PreferHdr)
905 .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
906 .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
907 .with_tone_mapping_mode(WindowToneMappingMode::Reinhard);
908 let app = Application::new()
909 .with_feathering_enabled(false)
910 .with_feather_width(2.25)
911 .with_window_render_options(options);
912 let clamped = Application::new().with_feather_width(-1.0);
913
914 assert!(!app.feathering_enabled());
915 assert_eq!(app.feather_width(), 2.25);
916 assert_eq!(clamped.feather_width(), 0.0);
917 assert_eq!(app.initial_window_render_options(), Some(options));
918 }
919
920 #[cfg(feature = "wgpu")]
921 #[test]
922 fn application_accepts_external_texture_registry() {
923 let registry = WgpuExternalTextureRegistry::new();
924 let app = Application::new().with_external_texture_registry(registry.clone());
925
926 assert!(app.external_texture_registry().is_some());
927 assert!(registry.context().is_none());
928 }
929}