1use crate::{
4 converters::convert_system_cursor_icon,
5 state::{CursorSource, PendingCursor},
6};
7#[cfg(feature = "custom_cursor")]
8use crate::{
9 custom_cursor::{
10 calculate_effective_rect, extract_and_transform_rgba_pixels, extract_rgba_pixels,
11 transform_hotspot, CustomCursorPlugin,
12 },
13 state::{CustomCursorCache, CustomCursorCacheKey},
14 WinitCustomCursor,
15};
16use bevy_app::{App, Last, Plugin};
17#[cfg(feature = "custom_cursor")]
18use bevy_asset::Assets;
19#[cfg(feature = "custom_cursor")]
20use bevy_ecs::system::Res;
21use bevy_ecs::{
22 change_detection::DetectChanges,
23 component::Component,
24 entity::Entity,
25 observer::Trigger,
26 query::With,
27 reflect::ReflectComponent,
28 system::{Commands, Local, Query},
29 world::{OnRemove, Ref},
30};
31#[cfg(feature = "custom_cursor")]
32use bevy_image::{Image, TextureAtlasLayout};
33use bevy_platform::collections::HashSet;
34use bevy_reflect::{std_traits::ReflectDefault, Reflect};
35use bevy_window::{SystemCursorIcon, Window};
36#[cfg(feature = "custom_cursor")]
37use tracing::warn;
38
39#[cfg(feature = "custom_cursor")]
40pub use crate::custom_cursor::{CustomCursor, CustomCursorImage};
41
42#[cfg(all(
43 feature = "custom_cursor",
44 target_family = "wasm",
45 target_os = "unknown"
46))]
47pub use crate::custom_cursor::CustomCursorUrl;
48
49pub(crate) struct CursorPlugin;
50
51impl Plugin for CursorPlugin {
52 fn build(&self, app: &mut App) {
53 #[cfg(feature = "custom_cursor")]
54 app.add_plugins(CustomCursorPlugin);
55
56 app.register_type::<CursorIcon>()
57 .add_systems(Last, update_cursors);
58
59 app.add_observer(on_remove_cursor_icon);
60 }
61}
62
63#[derive(Component, Debug, Clone, Reflect, PartialEq, Eq)]
65#[reflect(Component, Debug, Default, PartialEq, Clone)]
66pub enum CursorIcon {
67 #[cfg(feature = "custom_cursor")]
68 Custom(CustomCursor),
70 System(SystemCursorIcon),
72}
73
74impl Default for CursorIcon {
75 fn default() -> Self {
76 CursorIcon::System(Default::default())
77 }
78}
79
80impl From<SystemCursorIcon> for CursorIcon {
81 fn from(icon: SystemCursorIcon) -> Self {
82 CursorIcon::System(icon)
83 }
84}
85
86fn update_cursors(
87 mut commands: Commands,
88 windows: Query<(Entity, Ref<CursorIcon>), With<Window>>,
89 #[cfg(feature = "custom_cursor")] cursor_cache: Res<CustomCursorCache>,
90 #[cfg(feature = "custom_cursor")] images: Res<Assets<Image>>,
91 #[cfg(feature = "custom_cursor")] texture_atlases: Res<Assets<TextureAtlasLayout>>,
92 mut queue: Local<HashSet<Entity>>,
93) {
94 for (entity, cursor) in windows.iter() {
95 if !(queue.remove(&entity) || cursor.is_changed()) {
96 continue;
97 }
98
99 let cursor_source = match cursor.as_ref() {
100 #[cfg(feature = "custom_cursor")]
101 CursorIcon::Custom(CustomCursor::Image(c)) => {
102 let CustomCursorImage {
103 handle,
104 texture_atlas,
105 flip_x,
106 flip_y,
107 rect,
108 hotspot,
109 } = c;
110
111 let cache_key = CustomCursorCacheKey::Image {
112 id: handle.id(),
113 texture_atlas_layout_id: texture_atlas.as_ref().map(|a| a.layout.id()),
114 texture_atlas_index: texture_atlas.as_ref().map(|a| a.index),
115 flip_x: *flip_x,
116 flip_y: *flip_y,
117 rect: *rect,
118 };
119
120 if cursor_cache.0.contains_key(&cache_key) {
121 CursorSource::CustomCached(cache_key)
122 } else {
123 let Some(image) = images.get(handle) else {
124 warn!(
125 "Cursor image {handle:?} is not loaded yet and couldn't be used. Trying again next frame."
126 );
127 queue.insert(entity);
128 continue;
129 };
130
131 let (rect, needs_sub_image) =
132 calculate_effective_rect(&texture_atlases, image, texture_atlas, rect);
133
134 let (maybe_rgba, hotspot) = if *flip_x || *flip_y || needs_sub_image {
135 (
136 extract_and_transform_rgba_pixels(image, *flip_x, *flip_y, rect),
137 transform_hotspot(*hotspot, *flip_x, *flip_y, rect),
138 )
139 } else {
140 (extract_rgba_pixels(image), *hotspot)
141 };
142
143 let Some(rgba) = maybe_rgba else {
144 warn!("Cursor image {handle:?} not accepted because it's not rgba8 or rgba32float format");
145 continue;
146 };
147
148 let source = match WinitCustomCursor::from_rgba(
149 rgba,
150 rect.width() as u16,
151 rect.height() as u16,
152 hotspot.0,
153 hotspot.1,
154 ) {
155 Ok(source) => source,
156 Err(err) => {
157 warn!("Cursor image {handle:?} is invalid: {err}");
158 continue;
159 }
160 };
161
162 CursorSource::Custom((cache_key, source))
163 }
164 }
165 #[cfg(all(
166 feature = "custom_cursor",
167 target_family = "wasm",
168 target_os = "unknown"
169 ))]
170 CursorIcon::Custom(CustomCursor::Url(c)) => {
171 let cache_key = CustomCursorCacheKey::Url(c.url.clone());
172
173 if cursor_cache.0.contains_key(&cache_key) {
174 CursorSource::CustomCached(cache_key)
175 } else {
176 use crate::CustomCursorExtWebSys;
177 let source =
178 WinitCustomCursor::from_url(c.url.clone(), c.hotspot.0, c.hotspot.1);
179 CursorSource::Custom((cache_key, source))
180 }
181 }
182 CursorIcon::System(system_cursor_icon) => {
183 CursorSource::System(convert_system_cursor_icon(*system_cursor_icon))
184 }
185 };
186
187 commands
188 .entity(entity)
189 .insert(PendingCursor(Some(cursor_source)));
190 }
191}
192
193fn on_remove_cursor_icon(trigger: Trigger<OnRemove, CursorIcon>, mut commands: Commands) {
195 commands
197 .entity(trigger.target())
198 .try_insert(PendingCursor(Some(CursorSource::System(
199 convert_system_cursor_icon(SystemCursorIcon::Default),
200 ))));
201}