image.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. use dioxus_core::Event;
  2. pub type ImageEvent = Event<ImageData>;
  3. pub struct ImageData {
  4. inner: Box<dyn HasImageData>,
  5. }
  6. impl<E: HasImageData> From<E> for ImageData {
  7. fn from(e: E) -> Self {
  8. Self { inner: Box::new(e) }
  9. }
  10. }
  11. impl std::fmt::Debug for ImageData {
  12. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  13. f.debug_struct("ImageData")
  14. .field("load_error", &self.load_error())
  15. .finish()
  16. }
  17. }
  18. impl PartialEq for ImageData {
  19. fn eq(&self, other: &Self) -> bool {
  20. self.load_error() == other.load_error()
  21. }
  22. }
  23. impl ImageData {
  24. /// Create a new ImageData
  25. pub fn new(e: impl HasImageData) -> Self {
  26. Self { inner: Box::new(e) }
  27. }
  28. /// If the renderer encountered an error while loading the image
  29. pub fn load_error(&self) -> bool {
  30. self.inner.load_error()
  31. }
  32. pub fn downcast<T: 'static>(&self) -> Option<&T> {
  33. self.inner.as_any().downcast_ref::<T>()
  34. }
  35. }
  36. #[cfg(feature = "serialize")]
  37. #[derive(serde::Serialize, serde::Deserialize)]
  38. struct SerializedImageData {
  39. load_error: bool,
  40. }
  41. #[cfg(feature = "serialize")]
  42. impl From<&ImageData> for SerializedImageData {
  43. fn from(data: &ImageData) -> Self {
  44. Self {
  45. load_error: data.load_error(),
  46. }
  47. }
  48. }
  49. #[cfg(feature = "serialize")]
  50. impl HasImageData for SerializedImageData {
  51. fn as_any(&self) -> &dyn std::any::Any {
  52. self
  53. }
  54. fn load_error(&self) -> bool {
  55. self.load_error
  56. }
  57. }
  58. #[cfg(feature = "serialize")]
  59. impl serde::Serialize for ImageData {
  60. fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
  61. SerializedImageData::from(self).serialize(serializer)
  62. }
  63. }
  64. #[cfg(feature = "serialize")]
  65. impl<'de> serde::Deserialize<'de> for ImageData {
  66. fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
  67. let data = SerializedImageData::deserialize(deserializer)?;
  68. Ok(Self {
  69. inner: Box::new(data),
  70. })
  71. }
  72. }
  73. /// A trait for any object that has the data for an image event
  74. pub trait HasImageData: std::any::Any {
  75. /// If the renderer encountered an error while loading the image
  76. fn load_error(&self) -> bool;
  77. /// return self as Any
  78. fn as_any(&self) -> &dyn std::any::Any;
  79. }
  80. impl_event! [
  81. ImageData;
  82. /// onerror
  83. onerror
  84. /// onload
  85. onload
  86. ];