├── .gitignore ├── docs ├── demo.png └── struct_fields.png ├── bevy-contrib-inspector-derive ├── static │ ├── style.css │ └── script.js ├── Cargo.toml └── src │ ├── lib.rs │ ├── attrs.rs │ ├── as_html │ ├── mod.rs │ ├── as_html_enum.rs │ └── as_html_struct.rs │ └── inspectable.rs ├── CHANGELOG.md ├── LICENSE ├── examples ├── struct.rs └── example.rs ├── Cargo.toml ├── README.md ├── src ├── inspector_server.rs ├── plugin.rs ├── lib.rs └── html_impls.rs └── static └── vec2d_ashtml.js /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /index.html 3 | 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /docs/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakobhellermann/bevy-contrib-inspector/HEAD/docs/demo.png -------------------------------------------------------------------------------- /docs/struct_fields.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakobhellermann/bevy-contrib-inspector/HEAD/docs/struct_fields.png -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | display: flex; 3 | justify-content: center; 4 | margin-top: 2rem; 5 | } 6 | 7 | #inputs { 8 | display: table; 9 | border-spacing: 0.25rem 0.5rem; 10 | } 11 | 12 | .row { 13 | display: table-row; 14 | } 15 | 16 | .cell { 17 | display: table-cell; 18 | } 19 | 20 | .text-right { 21 | text-align: right; 22 | } -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy-contrib-inspector-derive" 3 | version = "0.5.0" 4 | authors = ["Jakob Hellermann "] 5 | edition = "2018" 6 | license = "MIT" 7 | description = "Implementation detail of the `bevy-contrib-inspector` crate" 8 | repository = "https://github.com/jakobhellermann/bevy-contrib-inspector" 9 | 10 | [lib] 11 | proc-macro = true 12 | 13 | [dependencies] 14 | syn = "1.0" 15 | quote = "1.0" 16 | proc-macro2 = "1.0" 17 | -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod as_html; 2 | mod attrs; 3 | mod inspectable; 4 | 5 | #[proc_macro_derive(Inspectable, attributes(inspectable))] 6 | pub fn inspectable(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 7 | let input = syn::parse_macro_input!(input as syn::DeriveInput); 8 | 9 | inspectable::DeriveData::expand(input).into() 10 | } 11 | 12 | #[proc_macro_derive(AsHtml)] 13 | pub fn as_html(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 14 | let input = syn::parse_macro_input!(input as syn::DeriveInput); 15 | 16 | as_html::expand(input).into() 17 | } 18 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | 4 | ## 0.5.0 5 | ### Added 6 | - Allow struct fields 7 | ### Changed: 8 | - the `submit_fn` in `AsHtml::as_html` is now a `String` instead of a `&'static str` 9 | 10 | ### Example: 11 | ```rust 12 | #[derive(AsHtml, Debug)] 13 | pub struct NoiseSettings { 14 | octaves: usize, 15 | frequency: f64, 16 | lacunarity: f64, 17 | persistence: f64, 18 | attenuation: f64, 19 | } 20 | 21 | #[derive(AsHtml, Debug, Default)] 22 | pub struct TupleStruct(String, String); 23 | ``` 24 | Your image title 25 | 26 | 27 | ## 0.4.0 28 | - update to bevy 0.4 -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/static/script.js: -------------------------------------------------------------------------------- 1 | const throttle = (func, limit) => { 2 | if (!limit) return func; 3 | 4 | let lastFunc, lastRan; 5 | return function () { 6 | const context = this, args = arguments; 7 | if (!lastRan) { 8 | func.apply(context, args); 9 | lastRan = Date.now(); 10 | } else { 11 | clearTimeout(lastFunc); 12 | lastFunc = setTimeout(function () { 13 | if ((Date.now() - lastRan) >= limit) { 14 | func.apply(context, args); 15 | lastRan = Date.now(); 16 | } 17 | }, limit - (Date.now() - lastRan)); 18 | } 19 | } 20 | } 21 | 22 | const handleChange = throttle((field, data) => { 23 | let body = field + ':' + data; 24 | return fetch("", { method: "PUT", body }).catch(e => { 25 | console.error(e); 26 | alert(e); 27 | }) 28 | }, handleChangeThrottle); // set in inspectable.rs -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/src/attrs.rs: -------------------------------------------------------------------------------- 1 | fn parse_inspectable_attributes( 2 | input: syn::parse::ParseStream, 3 | ) -> syn::Result> { 4 | let parse_attribute = |input: syn::parse::ParseStream| { 5 | let ident: syn::Ident = input.parse()?; 6 | let _eq_token: syn::Token![=] = input.parse()?; 7 | let expr: syn::Expr = input.parse()?; 8 | Ok((ident, expr)) 9 | }; 10 | 11 | input 12 | .parse_terminated::<_, syn::Token![,]>(parse_attribute) 13 | .map(IntoIterator::into_iter) 14 | } 15 | 16 | /// extracts [(min, 8), (field, vec2(1.0, 1.0))] from `#[inspectable(min = 8, field = vec2(1.0, 1.0))]`, 17 | pub fn inspectable_attributes( 18 | attrs: &[syn::Attribute], 19 | ) -> impl Iterator + '_ { 20 | attrs 21 | .iter() 22 | .filter(|attr| attr.path.get_ident().map_or(false, |p| p == "inspectable")) 23 | .flat_map(|attr| attr.parse_args_with(parse_inspectable_attributes).unwrap()) 24 | } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Jakob Hellermann 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /examples/struct.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_contrib_inspector::{AsHtml, Inspectable, InspectorPlugin}; 3 | 4 | #[derive(Inspectable, Default, Debug)] 5 | struct Data { 6 | noise_settings: NoiseSettings, 7 | tuple_struct: TupleStruct, 8 | } 9 | 10 | #[derive(AsHtml, Debug)] 11 | pub struct NoiseSettings { 12 | octaves: usize, 13 | frequency: f64, 14 | lacunarity: f64, 15 | persistence: f64, 16 | attenuation: f64, 17 | } 18 | 19 | #[derive(AsHtml, Debug, Default)] 20 | pub struct TupleStruct(String, String); 21 | 22 | impl Default for NoiseSettings { 23 | fn default() -> Self { 24 | Self { 25 | octaves: 0, 26 | frequency: 1.0, 27 | lacunarity: std::f64::consts::PI * 2.0 / 3.0, 28 | persistence: 1.0, 29 | attenuation: 2.0, 30 | } 31 | } 32 | } 33 | 34 | fn main() { 35 | App::build() 36 | .add_plugins(MinimalPlugins) 37 | .add_plugin(InspectorPlugin::::new()) 38 | .add_system(log.system()) 39 | .run(); 40 | } 41 | 42 | fn log(data: ChangedRes) { 43 | dbg!(&*data); 44 | } 45 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy-contrib-inspector" 3 | version = "0.5.1" 4 | authors = ["Jakob Hellermann "] 5 | edition = "2018" 6 | license = "MIT" 7 | description = "starts a webserver for visually editing bevy resources" 8 | readme = "README.md" 9 | repository = "https://github.com/jakobhellermann/bevy-contrib-inspector" 10 | keywords = ["bevy", "inspector", "visual", "editor", "game"] 11 | categories = ["development-tools::procedural-macro-helpers", "game-development", "gui", "visualization"] 12 | 13 | [features] 14 | native = ["webview_official"] 15 | 16 | [dependencies] 17 | bevy-contrib-inspector-derive = { path = "./bevy-contrib-inspector-derive" } 18 | # bevy-contrib-inspector-derive = "0.5" 19 | bevy = { version = "0.4", default-features = false, features = ["render"] } 20 | 21 | flume = { version = "0.10", default-features = false } 22 | tiny_http = "0.7" 23 | 24 | webbrowser = "0.5" 25 | # web-view = { version = "0.6", optional = true } 26 | webview_official = { version = "0.0.3", optional = true } 27 | 28 | [dev-dependencies] 29 | bevy = { version = "0.4", default-features = false, features = ["render", "bevy_wgpu", "x11"] } 30 | 31 | [profile.dev.package."*"] 32 | opt-level = 2 33 | -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/src/as_html/mod.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | 3 | mod as_html_enum; 4 | mod as_html_struct; 5 | 6 | pub struct DeriveDataEnum<'a> { 7 | ident: syn::Ident, 8 | variants: Vec<&'a syn::Variant>, 9 | } 10 | 11 | pub struct DeriveDataStruct<'a> { 12 | ident: syn::Ident, 13 | fields: Vec<&'a syn::Field>, 14 | } 15 | 16 | pub fn expand(input: syn::DeriveInput) -> TokenStream { 17 | match input.data { 18 | syn::Data::Enum(data) => { 19 | let variants = data 20 | .variants 21 | .iter() 22 | .inspect(|variant| { 23 | assert!(variant.fields.is_empty(), "only unit enums are supported"); 24 | }) 25 | .collect(); 26 | 27 | let data = DeriveDataEnum { 28 | ident: input.ident, 29 | variants, 30 | }; 31 | as_html_enum::to_tokens(data) 32 | } 33 | syn::Data::Struct(data) => as_html_struct::to_tokens(DeriveDataStruct { 34 | ident: input.ident, 35 | fields: data.fields.iter().collect(), 36 | }), 37 | syn::Data::Union(_) => panic!("unions are not supported"), 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/src/as_html/as_html_enum.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::quote; 3 | 4 | use crate::as_html::DeriveDataEnum; 5 | 6 | pub fn to_tokens(data: DeriveDataEnum<'_>) -> TokenStream { 7 | let DeriveDataEnum { ident, variants } = data; 8 | 9 | let html = html(variants.as_slice()); 10 | 11 | let parse_arms = variants.iter().map(|variant| { 12 | let var_ident = &variant.ident; 13 | let var_ident_str = var_ident.to_string(); 14 | 15 | quote! { #var_ident_str => Ok(#ident::#var_ident) } 16 | }); 17 | 18 | quote! { 19 | impl bevy_contrib_inspector::as_html::AsHtml for #ident { 20 | type Err = String; 21 | type Options = (); 22 | const DEFAULT_OPTIONS: Self::Options = (); 23 | 24 | fn as_html( 25 | shared: bevy_contrib_inspector::as_html::SharedOptions, 26 | (): Self::Options, 27 | submit_fn: String, 28 | ) -> String { 29 | #html 30 | } 31 | 32 | fn parse(value: &str) -> Result { 33 | match value { 34 | #(#parse_arms,)* 35 | _ => Err(value.to_string()), 36 | } 37 | } 38 | } 39 | } 40 | } 41 | 42 | fn html(variants: &[&syn::Variant]) -> TokenStream { 43 | let var_ident_strs = variants.iter().map(|v| v.ident.to_string()); 44 | 45 | quote! { 46 | let mut html = String::new(); 47 | html.push_str(&format!( 48 | r#" 49 |
50 | 51 |
"#, 52 | shared.label, 53 | )); 54 | 55 | for field in &[#(#var_ident_strs),*] { 56 | html.push_str(&format!( 57 | r#" 58 | 62 | "#, 63 | submit_fn, 64 | value = field, 65 | name = shared.label, 66 | checked=if format!("{:?}", shared.default) == *field { "checked" } else {""} 67 | )); 68 | } 69 | 70 | html.push_str(r#"
"#); 71 | html 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bevy-contrib-inspector 2 | 3 |
4 | 5 | 6 | Crates.io version 8 | 9 | 10 | 11 | docs.rs docs 13 | 14 | 15 | Download 17 |
18 |
19 | 20 | ## DISCLAIMER: you probably want to use [bevy-inspector-egui](https://github.com/jakobhellermann/bevy-inspector-egui) instead 21 | 22 | 23 | 24 | This crate provides the ability to annotate structs with a `#[derive(Inspectable)]`, 25 | which opens a web interface (by default on port 5676) where you can visually edit the values of your struct live. 26 | 27 | Your struct will then be available to you as a bevy resource. 28 | 29 | Your image title 30 | 31 | ## Example 32 | ```rust 33 | use bevy_contrib_inspector::Inspectable; 34 | 35 | #[derive(Inspectable, Default)] 36 | struct Data { 37 | should_render: bool, 38 | text: String, 39 | #[inspectable(min = 42.0, max = 100.0)] 40 | size: f32, 41 | } 42 | ``` 43 | Add the `InspectorPlugin` to your App. 44 | ```rust 45 | use bevy_contrib_inspector::InspectorPlugin; 46 | 47 | fn main() { 48 | App::build() 49 | .add_default_plugins() 50 | .add_plugin(InspectorPlugin::::new()) 51 | .add_system(your_system.system()) 52 | // ... 53 | .run(); 54 | } 55 | 56 | fn your_system(data: ChangedRes, mut query: Query<...>) { /* */ } 57 | ``` 58 | To automatically open the webbrowser when starting, run your program using `BEVY_INSPECTOR_OPEN=1 cargo run`. 59 | 60 | ## Attributes 61 | When deriving the `Inspectable` trait, you can set options such like the port the server will run on like so: 62 | ```rust 63 | #[derive(Inspectable, Default)] 64 | #[inspectable(port = 1234)] 65 | struct Data { 66 | #[inspectable(a = 1, b = 2, c = 3)] 67 | field: Type, 68 | } 69 | ``` 70 | The attribute on the struct will accept fields of the type `InspectableOptions`, 71 | while the attributes on the fields accept those of their `::Options`. 72 | 73 | ## Features 74 | `native`: Instead of opening the inspector window in a browser, start a webkit2gtk window. 75 | 76 | On ubuntu, the feature requires `sudo apt install libwebkit2gtk-4.0-dev` 77 | -------------------------------------------------------------------------------- /src/inspector_server.rs: -------------------------------------------------------------------------------- 1 | use flume::{unbounded as channel, Receiver, Sender}; 2 | use tiny_http::{Method, Request, Response, Server, StatusCode}; 3 | 4 | type Event = (String, String); 5 | 6 | pub struct InspectorServer { 7 | pub rx: Receiver, 8 | pub handle: std::thread::JoinHandle<()>, 9 | } 10 | 11 | type Error = Box; 12 | 13 | #[derive(Clone)] 14 | pub struct ServerConfig { 15 | html: String, 16 | } 17 | 18 | impl ServerConfig { 19 | pub fn new(html: String) -> Self { 20 | ServerConfig { html } 21 | } 22 | } 23 | 24 | fn handle_request( 25 | config: &ServerConfig, 26 | mut req: Request, 27 | tx: &Sender, 28 | ) -> Result<(), std::io::Error> { 29 | match req.method() { 30 | Method::Get => return handle_get(config, req), 31 | Method::Put => { 32 | if let Some(event) = parse_body(&mut req)? { 33 | tx.send(event).unwrap(); 34 | } 35 | } 36 | _ => {} 37 | } 38 | req.respond(Response::new_empty(StatusCode(200)))?; 39 | Ok(()) 40 | } 41 | 42 | fn handle_get(config: &ServerConfig, req: Request) -> Result<(), std::io::Error> { 43 | let content_type = 44 | tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"text/html"[..]).unwrap(); 45 | 46 | let mut response = Response::from_string(&config.html); 47 | response.add_header(content_type); 48 | req.respond(response) 49 | } 50 | fn parse_body(req: &mut Request) -> Result, std::io::Error> { 51 | let mut buf = Vec::with_capacity(req.body_length().unwrap_or_default()); 52 | let reader = req.as_reader(); 53 | reader.read_to_end(&mut buf)?; 54 | 55 | let invalid_data = |e| std::io::Error::new(std::io::ErrorKind::InvalidData, e); 56 | 57 | let event = String::from_utf8(buf).map_err(invalid_data)?; 58 | 59 | let mut iter = event.splitn(2, ':'); 60 | match (iter.next(), iter.next()) { 61 | (Some(field), Some(data)) => Ok(Some((field.to_string(), data.to_string()))), 62 | _ => Ok(None), 63 | } 64 | } 65 | 66 | impl InspectorServer { 67 | pub fn start_in_background(addr: &str, config: ServerConfig) -> Result { 68 | let (tx, rx) = channel(); 69 | 70 | let listener = Server::http(addr)?; 71 | 72 | let handle = std::thread::spawn(move || { 73 | for req in listener.incoming_requests() { 74 | if let Err(e) = handle_request(&config, req, &tx) { 75 | dbg!(e); 76 | } 77 | } 78 | }); 79 | 80 | Ok(InspectorServer { rx, handle }) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/plugin.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | 3 | use crate::inspector_server::{InspectorServer, ServerConfig}; 4 | use crate::Inspectable; 5 | 6 | #[derive(Default, Clone)] 7 | pub struct InspectorPlugin { 8 | marker: std::marker::PhantomData, 9 | } 10 | impl InspectorPlugin { 11 | pub fn new() -> InspectorPlugin { 12 | InspectorPlugin { 13 | marker: std::marker::PhantomData, 14 | } 15 | } 16 | } 17 | 18 | impl InspectorPlugin { 19 | fn check(server: Res, mut inspectable_data: ResMut) { 20 | if let Ok((field, data)) = server.rx.try_recv() { 21 | inspectable_data.update(&field, &data); 22 | } 23 | } 24 | 25 | fn start_server(commands: &mut Commands) { 26 | let config = ServerConfig::new(T::html()); 27 | 28 | let options = T::options(); 29 | 30 | let addr = format!("localhost:{}", options.port); 31 | let server = InspectorServer::start_in_background(&addr, config).unwrap(); 32 | 33 | if should_open_browser() { 34 | if let Err(e) = open_inspector_window(format!("http://{}", addr)) { 35 | eprintln!("failed to open {}: {}", addr, e); 36 | } 37 | } 38 | 39 | commands.insert_resource(server); 40 | } 41 | } 42 | 43 | #[cfg(not(feature = "native"))] 44 | fn open_inspector_window(addr: String) -> Result<(), std::io::Error> { 45 | webbrowser::open(&addr)?; 46 | Ok(()) 47 | } 48 | #[cfg(feature = "native")] 49 | fn open_inspector_window(addr: String) -> Result<(), std::convert::Infallible> { 50 | std::thread::spawn(move || { 51 | webview_official::WebviewBuilder::new() 52 | .width(800) 53 | .height(600) 54 | .url(&addr) 55 | .build() 56 | .run(); 57 | /*web_view::builder() 58 | .title("Bevy Inspector") 59 | .content(web_view::Content::Url(addr)) 60 | .user_data(()) 61 | .invoke_handler(|_webview, _arg| Ok(())) 62 | .run() 63 | .unwrap();*/ 64 | }); 65 | 66 | Ok(()) 67 | } 68 | 69 | #[cfg(feature = "native")] 70 | fn should_open_browser() -> bool { 71 | true 72 | } 73 | 74 | #[cfg(not(feature = "native"))] 75 | fn should_open_browser() -> bool { 76 | let is_confirmation = |var: String| match var.as_str() { 77 | "1" | "true" | "yes" | "y" => true, 78 | "0" | "false" | "no" | "n" => false, 79 | other => { 80 | eprintln!("unexpected value for BEVY_INSPECTOR_OPEN: {}", other); 81 | false 82 | } 83 | }; 84 | 85 | let variable = 86 | std::env::var("BEVY_INSPECTOR_OPEN").or_else(|_| std::env::var("BEVY_OPEN_INSPECTOR")); 87 | variable.map_or(false, is_confirmation) 88 | } 89 | 90 | impl Plugin for InspectorPlugin { 91 | fn build(&self, app: &mut AppBuilder) { 92 | app.add_resource(T::default()) 93 | .add_startup_system(Self::start_server.system()) 94 | .add_system(Self::check.system()); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /examples/example.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_contrib_inspector::{AsHtml, Inspectable, InspectorPlugin}; 3 | 4 | #[derive(AsHtml, Debug)] 5 | enum TextColor { 6 | White, 7 | Green, 8 | Blue, 9 | } 10 | 11 | #[derive(Inspectable, Debug)] 12 | struct Data { 13 | #[inspectable(min = 10.0, max = 70.0)] 14 | font_size: f32, 15 | text: String, 16 | show_square: bool, 17 | text_color: TextColor, 18 | color: Color, 19 | #[inspectable(min = Vec2::new(-200., -200.), max = Vec2::new(200., 200.))] 20 | position: Vec2, 21 | } 22 | impl Default for Data { 23 | fn default() -> Self { 24 | Data { 25 | font_size: 50.0, 26 | text: "Hello World!".to_string(), 27 | show_square: true, 28 | text_color: TextColor::White, 29 | color: Color::BLUE, 30 | position: Vec2::default(), 31 | } 32 | } 33 | } 34 | 35 | fn main() { 36 | App::build() 37 | .add_plugins(DefaultPlugins) 38 | .add_plugin(InspectorPlugin::::new()) 39 | .add_startup_system(setup.system()) 40 | .add_system(text_update_system.system()) 41 | .add_system(shape_update_system.system()) 42 | .run(); 43 | } 44 | 45 | fn text_update_system(data: Res, mut query: Query<&mut Text>) { 46 | for mut text in query.iter_mut() { 47 | text.value = format!("{}", data.text); 48 | text.style.font_size = data.font_size; 49 | text.style.color = match &data.text_color { 50 | TextColor::White => Color::WHITE, 51 | TextColor::Green => Color::GREEN, 52 | TextColor::Blue => Color::BLUE, 53 | }; 54 | } 55 | } 56 | 57 | fn shape_update_system( 58 | data: ChangedRes, 59 | mut materials: ResMut>, 60 | mut query: Query<(&Handle, &mut Transform)>, 61 | ) { 62 | for (color, mut transfrom) in query.iter_mut() { 63 | let material = materials.get_mut(color).unwrap(); 64 | material.color = data.color; 65 | 66 | if !data.show_square { 67 | transfrom.translation.x = 1000000.0; 68 | } else { 69 | transfrom.translation.x = data.position.x; 70 | transfrom.translation.y = data.position.y; 71 | } 72 | } 73 | } 74 | 75 | fn setup( 76 | commands: &mut Commands, 77 | asset_server: Res, 78 | mut materials: ResMut>, 79 | ) { 80 | let font_handle = asset_server.load("/usr/share/fonts/truetype/noto/NotoMono-Regular.ttf"); 81 | 82 | let color = materials.add(Color::BLUE.into()); 83 | 84 | commands 85 | .spawn(Camera2dBundle::default()) 86 | .spawn(CameraUiBundle::default()) 87 | .spawn(TextBundle { 88 | style: Style { 89 | align_self: AlignSelf::FlexEnd, 90 | ..Default::default() 91 | }, 92 | text: Text { 93 | value: "".to_string(), 94 | font: font_handle, 95 | style: TextStyle { 96 | font_size: 50.0, 97 | ..Default::default() 98 | }, 99 | ..Default::default() 100 | }, 101 | ..Default::default() 102 | }) 103 | .spawn(SpriteBundle { 104 | material: color, 105 | sprite: Sprite { 106 | size: Vec2::new(40.0, 40.0), 107 | ..Default::default() 108 | }, 109 | transform: Transform::from_translation(Vec3::default()), 110 | ..Default::default() 111 | }); 112 | } 113 | -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/src/as_html/as_html_struct.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::{quote, ToTokens}; 3 | 4 | use crate::as_html::DeriveDataStruct; 5 | 6 | pub fn to_tokens(data: DeriveDataStruct<'_>) -> TokenStream { 7 | let DeriveDataStruct { ident, fields } = data; 8 | 9 | let html = html(&ident, fields.as_slice()); 10 | 11 | let parse_arms = fields.iter().enumerate().map(|(i, field)| { 12 | let ty = &field.ty; 13 | let field_name = field_name(field, i); 14 | 15 | let accessor = field.ident.as_ref().map_or_else( 16 | || syn::Index::from(i).to_token_stream(), 17 | |name| quote!{#name} 18 | ); 19 | 20 | quote! { #field_name => self.#accessor = <#ty as bevy_contrib_inspector::AsHtml>::parse(value).map_err(|e| format!("{:?}", e))? } 21 | }); 22 | let tys = fields.iter().map(|field| &field.ty); 23 | 24 | quote! { 25 | #[allow(warnings)] 26 | impl bevy_contrib_inspector::as_html::AsHtml for #ident { 27 | type Err = String; 28 | type Options = (); 29 | const DEFAULT_OPTIONS: Self::Options = (); 30 | 31 | fn as_html( 32 | shared: bevy_contrib_inspector::as_html::SharedOptions, 33 | (): Self::Options, 34 | submit_fn: String, 35 | ) -> String { 36 | #html 37 | } 38 | 39 | fn register_header_footer( 40 | types: &mut std::collections::HashSet, 41 | header: &mut String, 42 | footer: &mut String, 43 | ) { 44 | #(<#tys as bevy_contrib_inspector::as_html::AsHtml>::register_header_footer(types, header, footer);)* 45 | } 46 | 47 | fn parse(_: &str) -> Result { 48 | unreachable!("AsHtml::update will be used instead") 49 | } 50 | 51 | fn update(&mut self, value: &str) -> Result<(), Self::Err> { 52 | let mut iter = value.splitn(2, ':'); 53 | let (field, value) = iter.next().zip(iter.next()) 54 | .ok_or_else(|| format!("expected ':', got '{}'", value))?; 55 | 56 | match field { 57 | #(#parse_arms,)* 58 | other => return Err(format!("unexpected field '{}'", other)) 59 | } 60 | 61 | Ok(()) 62 | } 63 | } 64 | } 65 | } 66 | 67 | fn field_name(field: &syn::Field, i: usize) -> String { 68 | field 69 | .ident 70 | .as_ref() 71 | .map_or_else(|| format!("#{}", i), |name| name.to_string()) 72 | } 73 | 74 | fn html(struct_name: &syn::Ident, fields: &[&syn::Field]) -> TokenStream { 75 | let fields = fields.into_iter().enumerate().map(|(i, field)| { 76 | let ty = &field.ty; 77 | let field_name = field_name(field, i); 78 | 79 | let as_html = quote! { <#ty as bevy_contrib_inspector::as_html::AsHtml> }; 80 | 81 | let submit_fn = quote! { 82 | format!("((value) => {submit_fn}('{field}:'+value))", submit_fn = submit_fn, field = #field_name) 83 | }; 84 | 85 | quote! { 86 | let shared_options = bevy_contrib_inspector::as_html::SharedOptions { 87 | label: std::borrow::Cow::Borrowed(#field_name), 88 | default: Default::default(), 89 | }; 90 | let octave_html = #as_html::as_html( 91 | shared_options, 92 | #as_html::DEFAULT_OPTIONS, 93 | #submit_fn, 94 | ); 95 | html.push_str(&octave_html); 96 | } 97 | }); 98 | 99 | let struct_name_str = struct_name.to_string(); 100 | 101 | quote! { 102 | let mut html = format!("{}", #struct_name_str); 103 | #(#fields)* 104 | html.push_str("
"); 105 | html 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /bevy-contrib-inspector-derive/src/inspectable.rs: -------------------------------------------------------------------------------- 1 | extern crate proc_macro; 2 | use proc_macro2::TokenStream; 3 | use quote::quote; 4 | 5 | struct Field<'a> { 6 | ident: &'a syn::Ident, 7 | ty: &'a syn::Type, 8 | attrs: &'a Vec, 9 | } 10 | 11 | pub struct DeriveData<'a> { 12 | ident: syn::Ident, 13 | fields: Vec>, 14 | attrs: &'a Vec, 15 | } 16 | 17 | impl<'a> DeriveData<'a> { 18 | pub fn expand(input: syn::DeriveInput) -> TokenStream { 19 | let data = match input.data { 20 | syn::Data::Struct(data) => data, 21 | _ => panic!("only structs are supported"), 22 | }; 23 | 24 | let fields = match data.fields { 25 | syn::Fields::Named(fields) => fields.named, 26 | _ => panic!("only named fields are supported"), 27 | }; 28 | 29 | let fields = fields 30 | .iter() 31 | .map(|field| { 32 | let ident = field.ident.as_ref().expect("field should be named"); 33 | Field { 34 | ident, 35 | ty: &field.ty, 36 | attrs: &field.attrs, 37 | } 38 | }) 39 | .collect(); 40 | 41 | let data = DeriveData { 42 | ident: input.ident, 43 | fields, 44 | attrs: &input.attrs, 45 | }; 46 | data.to_tokens() 47 | } 48 | 49 | pub fn to_tokens(&self) -> TokenStream { 50 | let DeriveData { 51 | ident, 52 | fields, 53 | attrs, 54 | } = self; 55 | 56 | let inspectable_fields = crate::attrs::inspectable_attributes(&attrs) 57 | .map(|(left, right)| quote! { #left: #right, }); 58 | let inspectable_options = quote! { 59 | bevy_contrib_inspector::InspectableOptions { 60 | #(#inspectable_fields)* 61 | ..Default::default() 62 | } 63 | }; 64 | 65 | let match_arms = fields.iter().map(|field| { 66 | let ident = field.ident; 67 | let ident_str = ident.to_string(); 68 | let ty = &field.ty; 69 | 70 | quote! { 71 | #ident_str => if let Err(e) = <#ty as bevy_contrib_inspector::as_html::AsHtml>::update(&mut self.#ident, &value) { 72 | eprintln!("failed to parse '{}': {:?}", #ident_str, e); 73 | } 74 | } 75 | }); 76 | 77 | let html = html(&fields); 78 | 79 | quote! { 80 | impl bevy_contrib_inspector::Inspectable for #ident { 81 | fn update(&mut self, field: &str, value: &str) { 82 | match field { 83 | #(#match_arms,)* 84 | _ => eprintln!("unexpected field '{}'", field), 85 | } 86 | } 87 | 88 | fn html() -> String { 89 | #html 90 | } 91 | 92 | fn options() -> bevy_contrib_inspector::InspectableOptions { 93 | #inspectable_options 94 | } 95 | } 96 | } 97 | } 98 | } 99 | 100 | fn html<'a>(fields: &[Field<'a>]) -> TokenStream { 101 | let fields_as_html = fields.iter().map(|field| { 102 | let ty = &field.ty; 103 | let attrs = &field.attrs; 104 | let ident = &field.ident; 105 | let ident_str = ident.to_string(); 106 | 107 | let as_html = quote! { <#ty as bevy_contrib_inspector::as_html::AsHtml> }; 108 | let option_fields = crate::attrs::inspectable_attributes(&attrs) 109 | .map(|(left, right)| quote! { options.#left = #right; }); 110 | 111 | quote! { 112 | let shared = bevy_contrib_inspector::as_html::SharedOptions { 113 | label: std::borrow::Cow::Borrowed(#ident_str), 114 | default: defaults.#ident, 115 | }; 116 | 117 | let mut options = #as_html::DEFAULT_OPTIONS; 118 | #(#option_fields)* 119 | 120 | let submit_fn = concat!("(value => handleChange('", #ident_str, "', value))").to_string(); 121 | 122 | inputs.push_str(&#as_html::as_html(shared, options, submit_fn)); 123 | } 124 | }); 125 | 126 | let css = include_str!("../static/style.css"); 127 | let js = include_str!("../static/script.js"); 128 | 129 | let tys = fields.iter().map(|field| &field.ty); 130 | 131 | quote! { 132 | let mut header = String::new(); 133 | let mut footer = String::new(); 134 | let mut field_types = std::collections::HashSet::::new(); 135 | 136 | #(<#tys as bevy_contrib_inspector::as_html::AsHtml>::register_header_footer(&mut field_types, &mut header, &mut footer);)* 137 | 138 | let mut inputs = String::new(); 139 | let defaults = ::default(); 140 | #(#fields_as_html)* 141 | 142 | 143 | format!( 144 | r#" 145 | 146 | 147 | 148 | 149 | {header} 150 | 151 | 152 | 153 | 157 | 158 |
159 | {inputs} 160 |
161 | 162 | {footer} 163 | 164 | "#, 165 | header=header, 166 | footer=footer, 167 | css=#css, 168 | js=#js, 169 | inputs=inputs, 170 | inspectable_throttle=10, // used in ../static/script.js 171 | ) 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate provides the ability to annotate structs with a `#[derive(Inspectable)]`, 2 | //! which opens a web interface (by default on port 5676) where you can visually edit the values of your struct live. 3 | //! 4 | //! Your struct will then be available to you as a bevy resource. 5 | //! 6 | //! ## Example 7 | //! ```rust 8 | //! use bevy_contrib_inspector::Inspectable; 9 | //! 10 | //! #[derive(Inspectable, Default)] 11 | //! struct Data { 12 | //! should_render: bool, 13 | //! text: String, 14 | //! #[inspectable(min = 42.0, max = 100.0)] 15 | //! size: f32, 16 | //! } 17 | //! ``` 18 | //! Add the [`InspectorPlugin`] to your App. 19 | //! ```rust,no_run 20 | //! use bevy_contrib_inspector::InspectorPlugin; 21 | //! # use bevy::prelude::*; 22 | //! 23 | //! # #[derive(bevy_contrib_inspector::Inspectable, Default)] struct Data {} 24 | //! fn main() { 25 | //! App::build() 26 | //! .add_plugins(DefaultPlugins) 27 | //! .add_plugin(InspectorPlugin::::new()) 28 | //! .add_system(your_system.system()) 29 | //! // ... 30 | //! .run(); 31 | //! } 32 | //! 33 | //! # fn your_system() {} 34 | //! // fn your_system(data: Res, mut query: Query<...>) { /* */ } 35 | //! ``` 36 | //! To automatically open the webbrowser when starting, run your program using `BEVY_INSPECTOR_OPEN=1 cargo run`. 37 | //! 38 | //! ## Attributes 39 | //! When deriving the [`Inspectable`] trait, you can set options such like the port the server will run on like so: 40 | //! ```rust 41 | //! # struct O { a: u8, b: u8, c: u8 } 42 | //! # #[derive(Default)] struct Type {} 43 | //! # impl bevy_contrib_inspector::AsHtml for Type { 44 | //! # type Err = (); 45 | //! # type Options = O; 46 | //! # const DEFAULT_OPTIONS: Self::Options = O { a: 0, b: 0, c: 0 }; 47 | //! # fn as_html(_: bevy_contrib_inspector::as_html::SharedOptions, _: Self::Options, _: &'static str) -> String { todo!() } 48 | //! # fn parse(_: &str) -> Result { todo!() } 49 | //! # } 50 | //! # 51 | //! # use bevy_contrib_inspector::Inspectable; 52 | //! #[derive(Inspectable, Default)] 53 | //! #[inspectable(port = 1234)] 54 | //! struct Data { 55 | //! #[inspectable(a = 1, b = 2, c = 3)] 56 | //! field: Type, 57 | //! } 58 | //! ``` 59 | //! The attribute on the struct will accept fields of the type [`InspectableOptions`], 60 | //! while the attributes on the fields accept those of their [`::Options`](as_html::AsHtml). 61 | mod html_impls; 62 | mod inspector_server; 63 | mod plugin; 64 | 65 | /// derives [AsHtml](trait.AsHtml.html) 66 | pub use bevy_contrib_inspector_derive::AsHtml; 67 | /// derives [Inspectable](trait.Inspectable.html) 68 | pub use bevy_contrib_inspector_derive::Inspectable; 69 | 70 | pub use plugin::InspectorPlugin; 71 | 72 | /// This trait describes how a struct should be rendered in HTML. 73 | /// It is meant to be derived, see the [crate-level docs](index.html) for that. 74 | pub trait Inspectable: Send + Sync + 'static { 75 | /// The HTML code which will be rendered from the webserver. 76 | fn html() -> String; 77 | /// When recieving a PUT request, its body will be parsed as `$field:$value`. 78 | /// The update function is supposed to parse the value into its correct type and set it on `self`. 79 | fn update(&mut self, field: &str, value: &str); 80 | /// Describes things like the webserver's port. Can be set with a `#[inspector(option = value)]` on the struct. 81 | fn options() -> InspectableOptions { 82 | InspectableOptions::default() 83 | } 84 | } 85 | 86 | /// The `InspectableOptions` control parameters like the webserver's port. 87 | /// 88 | /// They can be set when deriving the trait using `#[inspector(option = value)], as described in the [Attributes](index.html#attributes) section. 89 | pub struct InspectableOptions { 90 | pub port: u16, 91 | } 92 | impl Default for InspectableOptions { 93 | fn default() -> Self { 94 | InspectableOptions { port: 5676 } 95 | } 96 | } 97 | 98 | /// Attribute-Options for the [AsHtml] trait. 99 | pub mod as_html { 100 | pub use crate::html_impls::*; 101 | 102 | pub struct SharedOptions { 103 | pub label: std::borrow::Cow<'static, str>, 104 | pub default: T, 105 | } 106 | 107 | pub use crate::AsHtml; 108 | } 109 | 110 | /// controls how a type is rendered in HTML 111 | /// 112 | /// It also specifies how the type is parsed from a string 113 | /// and what attributes you can apply to it using `#[inspector(min = 1, max = 2)]` 114 | pub trait AsHtml: Sized + 'static { 115 | /// The parse error type 116 | type Err: std::fmt::Debug; 117 | /// The attibutes you can set for a field 118 | type Options; 119 | /// Default options for the `Options`-type 120 | const DEFAULT_OPTIONS: Self::Options; 121 | 122 | /// HTML that needs to go to the top of the page, e.g. ") 22 | } 23 | fn footer() -> &'static str { 24 | "" 25 | } 26 | 27 | // we overwrite this and only check for u8, since the footer and header is the same for all number types 28 | fn register_header_footer( 29 | types: &mut std::collections::HashSet, 30 | header: &mut String, 31 | footer: &mut String, 32 | ) { 33 | if types.insert(std::any::TypeId::of::()) { 34 | header.push_str(Self::header()); 35 | footer.push_str(Self::footer()); 36 | } 37 | } 38 | 39 | fn as_html(shared_options: crate::as_html::SharedOptions, options: Self::Options, submit_fn: String) -> String { 40 | format!(r#" 41 |
42 | 43 | 44 |
45 | "#, 46 | options.min, options.max, options.step, 47 | submit = submit_fn, 48 | value = shared_options.default, 49 | label = shared_options.label, 50 | ) 51 | } 52 | 53 | fn parse(value: &str) -> Result { 54 | value.parse() 55 | } 56 | } 57 | }; 58 | 59 | ( $($ty:ty),+ => $default_options:expr; $err:ty ) => { 60 | $(impl_ashtml_for_int!{ $ty => $default_options; $err })* 61 | } 62 | } 63 | 64 | impl_ashtml_for_int!(u8 => NumberAttributes { min: std::u8::MIN, max: std::u8::MAX, step: 1 } ; std::num::ParseIntError); 65 | impl_ashtml_for_int!(i8 => NumberAttributes { min: std::i8::MIN, max: std::i8::MAX, step: 1 } ; std::num::ParseIntError); 66 | 67 | impl_ashtml_for_int!(u16, u32, u64, u128, usize => NumberAttributes { min: 0, max: 100, step: 1 } ; std::num::ParseIntError); 68 | impl_ashtml_for_int!(i16, i32, i64, i128, isize => NumberAttributes { min: 0, max: 100, step: 1 } ; std::num::ParseIntError); 69 | 70 | impl_ashtml_for_int!(f32, f64 => NumberAttributes { min: 0.0, max: 1.0, step: 0.01 } ; std::num::ParseFloatError ); 71 | 72 | impl AsHtml for String { 73 | type Err = std::convert::Infallible; 74 | type Options = (); 75 | const DEFAULT_OPTIONS: Self::Options = (); 76 | 77 | fn as_html(shared: SharedOptions, (): Self::Options, submit_fn: String) -> String { 78 | format!( 79 | r#" 80 |
81 | 82 | 83 |
84 | "#, 85 | submit_fn, 86 | value = shared.default, 87 | label = shared.label, 88 | ) 89 | } 90 | 91 | fn parse(value: &str) -> Result { 92 | Ok(value.to_string()) 93 | } 94 | } 95 | 96 | impl AsHtml for bool { 97 | type Err = std::str::ParseBoolError; 98 | type Options = (); 99 | const DEFAULT_OPTIONS: Self::Options = (); 100 | 101 | fn as_html(shared: SharedOptions, (): Self::Options, submit_fn: String) -> String { 102 | format!( 103 | r#" 104 |
105 | 106 | 107 |
108 | "#, 109 | submit_fn, 110 | checked = if shared.default { "checked" } else { "" }, 111 | label = shared.label, 112 | ) 113 | } 114 | 115 | fn parse(value: &str) -> Result { 116 | value.parse() 117 | } 118 | } 119 | 120 | fn color_to_string(c: &Color) -> String { 121 | use std::fmt::Write; 122 | 123 | let mut s = String::with_capacity(6); 124 | s.push('#'); 125 | write!(s, "{:02x}", (c.r() * 255.0) as u8).unwrap(); 126 | write!(s, "{:02x}", (c.g() * 255.0) as u8).unwrap(); 127 | write!(s, "{:02x}", (c.b() * 255.0) as u8).unwrap(); 128 | s 129 | } 130 | fn string_to_color(s: &str) -> Result { 131 | if !s.starts_with('#') || !s.len() == 7 { 132 | return Err(()); 133 | } 134 | 135 | let r = u8::from_str_radix(&s[1..=2], 16).map_err(drop)?; 136 | let g = u8::from_str_radix(&s[3..=4], 16).map_err(drop)?; 137 | let b = u8::from_str_radix(&s[5..=6], 16).map_err(drop)?; 138 | 139 | let r = r as f32 / 255.0; 140 | let g = g as f32 / 255.0; 141 | let b = b as f32 / 255.0; 142 | 143 | Ok(Color::rgb(r, g, b)) 144 | } 145 | impl AsHtml for Color { 146 | type Err = (); 147 | type Options = (); 148 | 149 | const DEFAULT_OPTIONS: Self::Options = (); 150 | 151 | fn as_html(shared: SharedOptions, (): Self::Options, submit_fn: String) -> String { 152 | format!( 153 | r#"
154 | 155 | 156 |
"#, 157 | submit_fn, 158 | label = shared.label, 159 | default = color_to_string(&shared.default), 160 | ) 161 | } 162 | 163 | fn parse(value: &str) -> Result { 164 | string_to_color(value) 165 | } 166 | } 167 | 168 | pub struct Vec2Attributes { 169 | pub min: Vec2, 170 | pub max: Vec2, 171 | } 172 | impl AsHtml for Vec2 { 173 | type Err = (); 174 | type Options = Vec2Attributes; 175 | const DEFAULT_OPTIONS: Self::Options = Vec2Attributes { 176 | min: const_vec2!([-1.0, -1.0]), 177 | max: const_vec2!([1.0, 1.0]), 178 | }; 179 | 180 | fn as_html(shared: SharedOptions, options: Self::Options, submit_fn: String) -> String { 181 | format!( 182 | r#" 183 |
184 | 185 |
186 |
187 | ({default_x}, {default_y}) 188 | 196 |
197 |
198 |
199 | 207 | "#, 208 | default_x = shared.default.x, 209 | default_y = shared.default.y, 210 | min_x = options.min.x, 211 | min_y = options.min.y, 212 | max_x = options.max.x, 213 | max_y = options.max.y, 214 | submit_fn = submit_fn, 215 | label = shared.label, 216 | ) 217 | } 218 | 219 | fn footer() -> &'static str { 220 | concat!( 221 | "" 224 | ) 225 | } 226 | 227 | fn parse(value: &str) -> Result { 228 | let mut iter = value.splitn(2, ','); 229 | let x = iter.next().ok_or(())?; 230 | let y = iter.next().ok_or(())?; 231 | 232 | let x = x.parse().map_err(drop)?; 233 | let y = y.parse().map_err(drop)?; 234 | 235 | Ok(Vec2::new(x, y)) 236 | } 237 | } 238 | --------------------------------------------------------------------------------