Skip to main content

xur_std/gui/
types.rs

1use egui::Context;
2use facet::Facet;
3use xur_runtime::{RuntimeError, Value};
4
5#[derive(Facet, Clone)]
6#[facet(opaque)]
7pub struct EguiCtx(usize);
8
9unsafe impl Send for EguiCtx {}
10unsafe impl Sync for EguiCtx {}
11
12impl EguiCtx {
13    pub fn from_ctx(ctx: &Context) -> Self {
14        Self(ctx as *const Context as usize)
15    }
16
17    pub fn ctx(&self) -> &Context {
18        unsafe { &*(self.0 as *const Context) }
19    }
20}
21
22impl std::fmt::Display for EguiCtx {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "Ctx")
25    }
26}
27
28#[derive(Facet, Clone)]
29#[facet(opaque)]
30pub struct EguiUi(usize);
31
32unsafe impl Send for EguiUi {}
33unsafe impl Sync for EguiUi {}
34
35impl EguiUi {
36    pub fn from_ui(ui: &mut egui::Ui) -> Self {
37        Self(ui as *mut egui::Ui as usize)
38    }
39
40    #[allow(clippy::mut_from_ref)]
41    pub fn ui(&self) -> &mut egui::Ui {
42        unsafe { &mut *(self.0 as *mut egui::Ui) }
43    }
44}
45
46impl std::fmt::Display for EguiUi {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        write!(f, "Ui")
49    }
50}
51
52pub fn with_ctx(
53    val: &Value,
54    f: impl FnOnce(&Context) -> Result<Value, RuntimeError>,
55) -> Result<Value, RuntimeError> {
56    let Value::Native(obj) = val else {
57        return Err(RuntimeError::new("expected a `Ctx`"));
58    };
59    obj.with(|wrapper: &EguiCtx| f(wrapper.ctx()))
60        .ok_or_else(|| RuntimeError::new("expected a `Ctx`"))?
61}
62
63pub fn with_ui(
64    val: &Value,
65    f: impl FnOnce(&mut egui::Ui) -> Result<Value, RuntimeError>,
66) -> Result<Value, RuntimeError> {
67    let Value::Native(obj) = val else {
68        return Err(RuntimeError::new("expected a `Ui`"));
69    };
70    obj.with(|wrapper: &EguiUi| f(wrapper.ui()))
71        .ok_or_else(|| RuntimeError::new("expected a `Ui`"))?
72}
73
74/// A texture id handed to Xur scripts. Mirrors `egui::TextureId`: a `Managed`
75/// texture is one uploaded to egui (e.g. `load_texture_rgba`), a `User` texture
76/// is a native game texture registered by a backend (e.g. a Unity texture). The
77/// `image` widget renders either; scripts just hold and pass it.
78#[derive(Facet, Clone, Copy, PartialEq)]
79#[repr(u8)]
80pub enum Texture {
81    Managed(i64),
82    User(i64),
83}
84
85impl Texture {
86    /// The egui texture id this handle refers to.
87    pub fn texture_id(self) -> egui::TextureId {
88        match self {
89            Texture::Managed(id) => egui::TextureId::Managed(id as u64),
90            Texture::User(id) => egui::TextureId::User(id as u64),
91        }
92    }
93}