diff options
Diffstat (limited to 'engine/src/ui/view/world.rs')
| -rw-r--r-- | engine/src/ui/view/world.rs | 2314 |
1 files changed, 2314 insertions, 0 deletions
diff --git a/engine/src/ui/view/world.rs b/engine/src/ui/view/world.rs new file mode 100644 index 0000000..81c2377 --- /dev/null +++ b/engine/src/ui/view/world.rs @@ -0,0 +1,2314 @@ +use std::any::{Any, TypeId}; +use std::borrow::Cow; +use std::io::Cursor; +use std::ops::{Deref, DerefMut}; + +use crate::color::{Rgb, Rgba}; +use crate::ecs::actions::Actions; +use crate::ecs::component::local::Local; +use crate::ecs::component::{ + Handle as ComponentHandle, + Info as ComponentInfo, + Parts as ComponentParts, +}; +use crate::ecs::entity::{Handle as EntityHandle, Name as EntityName}; +use crate::ecs::sole::Single; +use crate::ecs::uid::Uid; +use crate::ecs::util::Either; +use crate::ecs::{Component, Query, World}; +use crate::image::{Format as ImageFormat, Image}; +use crate::reflection::{ + Enum as EnumReflection, + EnumVariant as EnumVariantReflection, + GetError as ReflectionGetError, + LiteralType, + Struct as StructReflection, + Type as TypeReflection, + Visibility, +}; +use crate::ui::dear_imgui::{ + bindings as dear_imgui_bindings, + Context as DearImguiContext, +}; + +const BUTTON_RED_NORMAL: [f32; 4] = [124.0, 52.0, 39.0, 255.0]; +const BUTTON_RED_HOVERED: [f32; 4] = [181.0, 76.0, 57.0, 255.0]; +const BUTTON_RED_ACTIVE: [f32; 4] = [162.0, 68.0, 51.0, 255.0]; + +#[derive(Default, Component)] +pub struct State +{ + spawning_entity: Option<Uid>, + popup_state: Option<PopupState>, + textures: Option<Textures>, +} + +pub fn show( + query: Query<()>, + mut dear_imgui_context: Single<DearImguiContext>, + mut state: Local<State>, + world: &World, + mut actions: Actions, +) -> Result<(), crate::Error> +{ + let dear_imgui_context = dear_imgui_context.get_mut()?; + + let State { + spawning_entity, + popup_state, + textures, + } = &mut *state; + + let textures = textures.get_or_insert_with(|| Textures::new(dear_imgui_context)); + + let Some(frame) = dear_imgui_context.frame() else { + return Ok(()); + }; + + frame + .window("World") + .size([600.0, 400.0], dear_imgui_bindings::Condition::Once) + .build(|| { + create_spawn_button_widgets( + frame, + spawning_entity, + popup_state, + world, + &mut actions, + ); + + frame.spacing(); + frame.spacing(); + + for ent_handle in &query.into_flexible_query() { + create_entity_widgets( + frame, + popup_state, + textures, + &ent_handle, + world, + &mut actions, + ); + } + + let popup_closed = match popup_state { + Some(PopupState::AddComponent(popup_state)) => { + show_add_component_popup(frame, popup_state, &mut actions) + } + Some(PopupState::RenameEntity(popup_state)) => { + show_rename_entity_popup(frame, popup_state, &mut actions, world) + } + _ => false, + }; + + if popup_closed { + *popup_state = None; + } + }); + + Ok(()) +} + +fn create_texture( + dear_imgui_context: &mut DearImguiContext, + image: Image, +) -> dear_imgui_bindings::ManagedTextureId +{ + let image = image.into_rgba8(); + + let mut texture_data = dear_imgui_bindings::OwnedTextureData::new(); + + texture_data.create( + dear_imgui_bindings::TextureFormat::RGBA32, + image.dimensions().width, + image.dimensions().height, + ); + + texture_data.set_data(image.as_bytes()); + + dear_imgui_context.register_texture(texture_data) +} + +fn create_spawn_button_widgets( + frame: &dear_imgui_bindings::Ui, + spawning_entity: &mut Option<Uid>, + popup_state: &mut Option<PopupState>, + world: &World, + actions: &mut Actions, +) +{ + let _disabled_token = frame.begin_disabled_with_cond(spawning_entity.is_some()); + + if frame.button("Spawn") { + let new_ent_id = actions.spawn(()); + + *spawning_entity = Some(new_ent_id); + } + + if let Some(spawning_ent) = &spawning_entity { + if let Some(spawned_ent) = world.get_entity(*spawning_ent) { + let spawned_ent_title = create_entity_title(&spawned_ent); + + if enter_add_component_popup_state( + popup_state, + &spawned_ent, + &spawned_ent_title, + world, + ) { + *spawning_entity = None; + } + } + } +} + +fn create_entity_widgets( + frame: &dear_imgui_bindings::Ui, + popup_state: &mut Option<PopupState>, + textures: &Textures, + ent_handle: &EntityHandle, + world: &World, + actions: &mut Actions, +) +{ + if ent_handle.component_ids().next().is_some() + && !ent_handle.component_ids().any(|comp_id| { + world.get_entity(comp_id).is_some_and(|comp_ent| { + comp_ent + .get::<ComponentInfo>() + .is_some_and(|comp_info| comp_info.type_reflection.is_some()) + }) + }) + { + return; + } + + let ent_title = create_entity_title(&ent_handle); + + let mut is_open = false; + + frame + .table(&format!("ent_{}_table", ent_handle.uid())) + .headers(false) + .sizing_policy(dear_imgui_bindings::TableSizingPolicy::FixedFit) + .columns([ + dear_imgui_bindings::TableColumnSetup::new("a") + .fixed_width(frame.content_region_avail_width() * 0.8), + dear_imgui_bindings::TableColumnSetup::new("b"), + dear_imgui_bindings::TableColumnSetup::new("c"), + dear_imgui_bindings::TableColumnSetup::new("d"), + ]) + .build(|frame| { + frame.table_next_row(); + + frame.table_next_column(); + + is_open = frame + .collapsing_header(&ent_title, dear_imgui_bindings::TreeNodeFlags::NONE); + + frame.table_next_column(); + + create_add_component_button_widget( + frame, + &ent_handle, + &ent_title, + popup_state, + world, + ); + + frame.table_next_column(); + + create_despawn_button_widget(frame, textures, ent_handle, actions); + + frame.table_next_column(); + + create_rename_entity_button_widget( + frame, + textures, + ent_handle, + &ent_title, + popup_state, + ); + }); + + if is_open { + for component_id in ent_handle.component_ids() { + if component_id.is_pair() { + create_pair_component_widgets( + frame, + textures, + ent_handle, + component_id, + world, + actions, + ); + + frame.spacing(); + + continue; + } + + create_component_widgets(frame, ent_handle, component_id, world, actions); + } + } +} + +fn create_component_widgets( + frame: &dear_imgui_bindings::Ui, + ent_handle: &EntityHandle, + component_id: Uid, + world: &World, + actions: &mut Actions, +) +{ + let Some(component_info) = world + .get_entity(component_id) + .and_then(|comp_ent| comp_ent.get::<ComponentInfo>()) + else { + return; + }; + + let Some(component_type) = component_info.type_reflection else { + return; + }; + + let Some(mut component) = ent_handle.get_any_by_id_mut(component_id) else { + unreachable!(); + }; + + { + let _color_token = frame.push_style_color( + dear_imgui_bindings::StyleColor::Button, + BUTTON_RED_NORMAL.map(|num| num / 255.0), + ); + + let _color_token_b = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonHovered, + BUTTON_RED_HOVERED.map(|num| num / 255.0), + ); + + let _color_token_c = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonActive, + BUTTON_RED_ACTIVE.map(|num| num / 255.0), + ); + + if frame.small_button(format!( + "X##world_view_entity_{}_remove_component_button_{}", + ent_handle.uid(), + component_info.name + )) { + actions.remove_components(ent_handle.uid(), [component_id]); + } + } + + frame.same_line(); + + let mut component_changed = false; + + create_item_title_widget( + frame, + component_info.name, + &ItemType::Reflected(component_type), + None, + ); + + let item_type = ItemType::Reflected(component_type); + + let _token = item_type.indent_or_same_line(frame); + + add_item_to_frame( + frame, + ItemRef::Mutable(&mut *component), + &mut component_changed, + ItemInfo { + item_title: component_info.name, + item_tag: &format!( + "world_view_entity_{}_component_{}", + ent_handle.uid(), + component_info.name, + ), + item_type_name: None, + item_type, + item_is_read_only: false, + }, + &[], + ); + + frame.spacing(); + + if component_changed { + component.set_changed(); + } +} + +fn create_pair_component_widgets( + frame: &dear_imgui_bindings::Ui, + textures: &Textures, + ent_handle: &EntityHandle, + pair_id: Uid, + world: &World, + actions: &mut Actions, +) +{ + { + let _color_token = frame.push_style_color( + dear_imgui_bindings::StyleColor::Button, + BUTTON_RED_NORMAL.map(|num| num / 255.0), + ); + + let _color_token_b = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonHovered, + BUTTON_RED_HOVERED.map(|num| num / 255.0), + ); + + let _color_token_c = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonActive, + BUTTON_RED_ACTIVE.map(|num| num / 255.0), + ); + + if frame.small_button(format!( + "X##world_view_entity_{}_remove_component_button_{}", + ent_handle.uid(), + pair_id + )) { + actions.remove_components(ent_handle.uid(), [pair_id]); + } + } + + frame.same_line(); + + let relation_comp_info_or_ent_name = + get_comp_info_or_ent_name(world, pair_id.relation()); + + let relation_name: Cow<'_, str> = match &relation_comp_info_or_ent_name { + Some(Either::A(comp_info)) => comp_info.name.into(), + Some(Either::B(ent_name)) => format!("🌐 {}", ent_name.name).into(), + None => format!("<unnamed> {}", pair_id.relation()).into(), + }; + + let target_comp_info_or_ent_name = get_comp_info_or_ent_name(world, pair_id.target()); + + let target_name: Cow<'_, str> = match &target_comp_info_or_ent_name { + Some(Either::A(comp_info)) => comp_info.name.into(), + Some(Either::B(ent_name)) => format!("🌐 {}", ent_name.name).into(), + None => format!("<unnamed> {}", pair_id.target()).into(), + }; + + // TODO: Make relation & target ids editable + + frame.text(format!("({relation_name}, {target_name})")); + + let Some(mut pair_data) = ent_handle.get_any_by_id_mut(pair_id) else { + unreachable!(); + }; + + let pair_data_ty_id = (*pair_data).type_id(); + + let Some(pair_data_comp_info) = [ + &relation_comp_info_or_ent_name, + &target_comp_info_or_ent_name, + ] + .map(Option::as_ref) + .map(|item| item.and_then(Either::as_a)) + .into_iter() + .flatten() + .find(|comp_info| comp_info.ty_id == pair_data_ty_id) else { + return; + }; + + let Some(pair_data_ty) = pair_data_comp_info.type_reflection else { + frame.same_line(); + + frame.image(textures.warning_icon_tex_id, [16.0, 16.0]); + + if frame.is_item_hovered() { + frame.tooltip_text(format!( + "Pair data type {} does not have reflection", + pair_data_comp_info.name + )); + } + + return; + }; + + let _indent = frame.begin_indent(); + + let mut component_changed = false; + + create_item_title_widget( + frame, + pair_data_comp_info.name, + &ItemType::Reflected(pair_data_ty), + None, + ); + + let item_type = ItemType::Reflected(pair_data_ty); + + let _token = item_type.indent_or_same_line(frame); + + add_item_to_frame( + frame, + ItemRef::Mutable(&mut *pair_data), + &mut component_changed, + ItemInfo { + item_title: pair_data_comp_info.name, + item_tag: &format!( + "world_view_entity_{}_pair_component_{pair_id}", + ent_handle.uid(), + ), + item_type_name: None, + item_type, + item_is_read_only: false, + }, + &[], + ); + + // The pair component is not set as changed here since events do not support + // pairs as event targets +} + +fn get_comp_info_or_ent_name( + world: &World, + id: Uid, +) -> Option<Either<ComponentHandle<'_, ComponentInfo>, ComponentHandle<'_, EntityName>>> +{ + let ent = world.get_entity(id)?; + + if let Some(component_info) = ent.get::<ComponentInfo>() { + return Some(Either::A(component_info)); + } + + if let Some(entity_name) = ent.get::<EntityName>() { + return Some(Either::B(entity_name)); + } + + None +} + +fn create_add_component_button_widget( + frame: &dear_imgui_bindings::Ui, + ent_handle: &EntityHandle, + ent_title: &str, + popup_state: &mut Option<PopupState>, + world: &World, +) +{ + let _color_token = frame.push_style_color( + dear_imgui_bindings::StyleColor::Button, + [49.0, 89.0, 28.0, 255.0].map(|num| num / 255.0), + ); + + let _color_token_b = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonHovered, + [100.0, 181.0, 57.0, 255.0].map(|num| num / 255.0), + ); + + let _color_token_c = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonActive, + [90.0, 162.0, 51.0, 255.0].map(|num| num / 255.0), + ); + + let is_button_clicked = frame.button(format!( + "+##add_component_to_entity_button_{}", + ent_handle.uid() + )); + + if is_button_clicked { + enter_add_component_popup_state(popup_state, ent_handle, ent_title, world); + } +} + +fn create_despawn_button_widget( + frame: &dear_imgui_bindings::Ui, + textures: &Textures, + ent_handle: &EntityHandle, + actions: &mut Actions, +) +{ + let _color_token = frame.push_style_color( + dear_imgui_bindings::StyleColor::Button, + BUTTON_RED_NORMAL.map(|num| num / 255.0), + ); + + let _color_token_b = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonHovered, + BUTTON_RED_HOVERED.map(|num| num / 255.0), + ); + + let _color_token_c = frame.push_style_color( + dear_imgui_bindings::StyleColor::ButtonActive, + BUTTON_RED_ACTIVE.map(|num| num / 255.0), + ); + + if frame + .image_button_config( + &format!("ent_{}_despawn_button", ent_handle.uid()), + textures.despawn_icon_tex_id, + [14.0, 14.0], + ) + .build() + { + actions.despawn(ent_handle.uid()); + } +} + +fn create_rename_entity_button_widget( + frame: &dear_imgui_bindings::Ui, + textures: &Textures, + ent_handle: &EntityHandle, + ent_title: &str, + popup_state: &mut Option<PopupState>, +) +{ + if frame + .image_button_config( + &format!("ent_{}_rename_button", ent_handle.uid()), + textures.edit_icon_tex_id, + [16.0, 16.0], + ) + .build() + { + enter_rename_entity_popup_state(popup_state, ent_handle, ent_title); + } +} + +fn enter_rename_entity_popup_state( + popup_state: &mut Option<PopupState>, + ent_handle: &EntityHandle, + ent_title: &str, +) -> bool +{ + if popup_state.is_some() { + return false; + } + + *popup_state = Some(PopupState::RenameEntity(RenameEntityPopupState { + popup_name: format!("Rename entity {ent_title}"), + target_entity_id: ent_handle.uid(), + new_entity_name: String::with_capacity(32), + })); + + true +} + +fn show_rename_entity_popup( + frame: &dear_imgui_bindings::Ui, + popup_state: &mut RenameEntityPopupState, + actions: &mut Actions, + world: &World, +) -> bool +{ + frame.open_popup(&popup_state.popup_name); + + let mut is_opened = true; + + let should_close = + frame.modal_popup_with_opened(&popup_state.popup_name, &mut is_opened, || { + frame.set_window_size([ + frame.calc_text_size(&popup_state.popup_name)[0] + 32.0, + 120.0, + ]); + + frame.spacing(); + frame.spacing(); + + frame.text("Name:"); + frame.same_line(); + + frame + .input_text( + "##rename_entity_popup_new_name_input", + &mut popup_state.new_entity_name, + ) + .build(); + + frame.spacing(); + frame.spacing(); + + let rename_text_size = frame.calc_text_size("Rename"); + + if frame.button_with_size( + "Rename##rename_entity_popup_rename_button", + [rename_text_size[0] * 2.0, rename_text_size[1] * 2.0], + ) { + let Some(target_ent) = world.get_entity(popup_state.target_entity_id) + else { + tracing::error!( + entity = ?popup_state.target_entity_id, + "Cannot rename entity: entity no longer exists" + ); + return true; + }; + + if let Some(mut target_ent_name) = target_ent.get_mut::<EntityName>() { + target_ent_name.name = popup_state.new_entity_name.clone().into(); + } else { + actions.add_components( + popup_state.target_entity_id, + (EntityName { + name: popup_state.new_entity_name.clone().into(), + },), + ); + } + + return true; + } + + false + }); + + if let Some(true) = should_close { + return true; + } + + if !is_opened { + return true; + } + + false +} + +fn enter_add_component_popup_state( + popup_state: &mut Option<PopupState>, + ent_handle: &EntityHandle, + ent_title: &str, + world: &World, +) -> bool +{ + if popup_state.is_some() { + return false; + } + + let popup_name = format!("Add component to {ent_title}"); + + let mut searchable_components = world + .query::<(&ComponentInfo,)>() + .iter_with_euids() + .map(|(id, (component_info,))| { + let user_creatable = if component_info.is_sole { + ComponentUserCreatable::No { reason: "is a sole" } + } else if component_info.type_reflection.is_none() { + ComponentUserCreatable::No { reason: "no type reflection" } + } else if component_info + .type_reflection + .is_some_and(|ty| !ty.has_default_value()) + { + ComponentUserCreatable::No { reason: "no default value" } + } else if !get_whole_type_is_user_editable( + component_info.type_reflection, + component_info.ty_id, + ) { + ComponentUserCreatable::No { + reason: "whole component is not user editable", + } + } else { + ComponentUserCreatable::Yes + }; + + (id, component_info.clone(), user_creatable) + }) + .collect::<Vec<_>>(); + + searchable_components.sort_by_key(|(_, _, user_creatable)| *user_creatable); + + *popup_state = Some(PopupState::AddComponent(AddComponentPopupState { + popup_name: popup_name.clone(), + target_entity_id: ent_handle.uid(), + search_text: String::with_capacity(20), + searched_components: searchable_components.clone(), + searchable_components, + selected_search_result: -1, + new_component: None, + })); + + true +} + +fn show_add_component_popup( + frame: &dear_imgui_bindings::Ui, + add_component_popup_state: &mut AddComponentPopupState, + actions: &mut Actions, +) -> bool +{ + frame.open_popup(&add_component_popup_state.popup_name); + + let mut is_opened = true; + + let should_close = frame.modal_popup_with_opened( + &add_component_popup_state.popup_name, + &mut is_opened, + || { + frame.set_window_size([700.0, 600.0]); + + frame.spacing(); + frame.spacing(); + + frame.text("Search:"); + frame.same_line(); + + if frame + .input_text( + "##add_component_popup_search_input", + &mut add_component_popup_state.search_text, + ) + .build() + { + add_component_popup_state.searched_components = add_component_popup_state + .searchable_components + .iter() + .cloned() + .filter(|(_, searchable_comp_info, _)| { + searchable_comp_info + .name + .contains(&add_component_popup_state.search_text) + }) + .collect(); + + add_component_popup_state.selected_search_result = -1; + } + + frame.spacing(); + frame.spacing(); + + let _item_width_token = frame.push_item_width(-1.0); + + if frame + .list_box_config("##add_component_popup_search_results") + .build_extended( + frame, + &mut add_component_popup_state.selected_search_result, + &add_component_popup_state.searched_components, + &|(_, comp_info, comp_user_creatable)| ListBoxItem { + label: comp_info.name.into(), + disabled: matches!( + comp_user_creatable, + ComponentUserCreatable::No { .. } + ), + hover_tooltip: match comp_user_creatable { + ComponentUserCreatable::Yes => None, + ComponentUserCreatable::No { reason } => Some( + format!("Component cannot be selected: {reason}").into(), + ), + }, + }, + ) + { + let (selected_comp_id, selected_comp_info, _) = add_component_popup_state + .searched_components + [add_component_popup_state.selected_search_result as usize] + .clone(); + + let Some(selected_component_type) = selected_comp_info.type_reflection + else { + unreachable!(); + }; + + let Some(selected_comp_default_value) = + selected_component_type.default_value() + else { + unreachable!(); // Only components with default values are selectable + }; + + add_component_popup_state.new_component = Some(( + selected_comp_default_value, + selected_comp_info, + selected_comp_id, + )); + } + + frame.spacing(); + frame.spacing(); + frame.spacing(); + + if let Some((new_component, new_component_info, _)) = + add_component_popup_state.new_component.as_mut() + { + let mut component_changed = false; + + let Some(new_component_type) = new_component_info.type_reflection else { + unreachable!(); + }; + + create_item_title_widget( + frame, + new_component_info.name, + &ItemType::Reflected(new_component_type), + None, + ); + + let item_type = ItemType::Reflected(new_component_type); + + let _token = item_type.indent_or_same_line(frame); + + add_item_to_frame( + frame, + ItemRef::Mutable(&mut **new_component), + &mut component_changed, + ItemInfo { + item_title: new_component_info.name, + item_tag: &format!( + "add_component_popup_component_{}", + new_component_info.name, + ), + item_type_name: None, + item_type, + item_is_read_only: false, + }, + &[], + ); + + frame.spacing(); + frame.spacing(); + frame.spacing(); + } + + let _disabled = frame.begin_disabled_with_cond( + add_component_popup_state.new_component.is_none(), + ); + + let add_text_size = frame.calc_text_size("Add"); + + if frame.button_with_size( + "Add##add_component_popup_add_button", + [add_text_size[0] * 2.0, add_text_size[1] * 2.0], + ) { + if let Some((new_component_data, new_component_info, new_component_id)) = + add_component_popup_state.new_component.take() + { + actions.add_components( + add_component_popup_state.target_entity_id, + [ComponentParts::from_component_info( + &new_component_info, + new_component_id, + new_component_data, + )], + ); + + return true; + } + } + + false + }, + ); + + if let Some(true) = should_close { + return true; + } + + if !is_opened { + return true; + } + + false +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum ComponentUserCreatable +{ + Yes, + No + { + reason: &'static str, + }, +} + +struct ItemInfo<'a> +{ + item_title: &'a str, + item_tag: &'a str, + item_type_name: Option<&'static str>, + item_type: ItemType, + item_is_read_only: bool, +} + +enum ItemType +{ + Reflected(&'static TypeReflection), + String, + CowStr, + Color(ColorItemType, LiteralType), +} + +impl ItemType +{ + fn spans_multiple_rows(&self) -> bool + { + match self { + Self::Reflected( + TypeReflection::Struct(_) + | TypeReflection::Array(_) + | TypeReflection::Slice(_), + ) => true, + Self::Reflected(TypeReflection::Enum(enum_ty)) => !enum_ty.is_unit_only, + Self::Reflected(TypeReflection::Reference(ref_ty)) => { + ItemType::Reflected(ref_ty.ty).spans_multiple_rows() + } + Self::Color(..) => false, + Self::Reflected(TypeReflection::Literal(_)) | Self::String | Self::CowStr => { + false + } + Self::Reflected(_) => unimplemented!(), + } + } + + fn indent_or_same_line<'frame>( + &self, + frame: &'frame dear_imgui_bindings::Ui, + ) -> Option<dear_imgui_bindings::IndentToken<'frame>> + { + if self.spans_multiple_rows() { + return Some(frame.begin_indent()); + } + + frame.same_line(); + + None + } +} + +#[derive(Debug)] +enum ColorItemType +{ + Rgb, + Rgba, +} + +fn get_item_type(ty: Option<&'static TypeReflection>, type_id: TypeId) + -> Option<ItemType> +{ + if let Some(TypeReflection::Struct(_)) = ty { + if type_id == TypeId::of::<Rgb<f32>>() { + return Some(ItemType::Color(ColorItemType::Rgb, LiteralType::F32)); + } + if type_id == TypeId::of::<Rgb<u8>>() { + return Some(ItemType::Color(ColorItemType::Rgb, LiteralType::U8)); + } + + if type_id == TypeId::of::<Rgba<f32>>() { + return Some(ItemType::Color(ColorItemType::Rgba, LiteralType::F32)); + } + if type_id == TypeId::of::<Rgba<u8>>() { + return Some(ItemType::Color(ColorItemType::Rgba, LiteralType::U8)); + } + } + + if let Some(ty) = ty { + return Some(ItemType::Reflected(ty)); + } else if type_id == TypeId::of::<String>() { + Some(ItemType::String) + } else if type_id == TypeId::of::<Cow<'static, str>>() { + Some(ItemType::CowStr) + } else { + None + } +} + +enum ItemRef<'item> +{ + Mutable(&'item mut dyn Any), + Immutable(&'item dyn Any), +} + +impl<'item> ItemRef<'item> +{ + fn get_struct_field( + &mut self, + ty: &StructReflection, + field_index: usize, + ) -> Result<ItemRef<'_>, ReflectionGetError> + { + match self { + ItemRef::Mutable(item) => { + (ty.try_get_field_mut)(*item, field_index).map(ItemRef::Mutable) + } + ItemRef::Immutable(item) => { + (ty.try_get_field)(*item, field_index).map(ItemRef::Immutable) + } + } + } + + fn get_enum_variant_field( + &mut self, + variant: &EnumVariantReflection, + field_index: usize, + ) -> Result<ItemRef<'_>, ReflectionGetError> + { + match self { + ItemRef::Mutable(item) => { + (variant.try_get_field_mut)(*item, field_index).map(ItemRef::Mutable) + } + ItemRef::Immutable(item) => { + (variant.try_get_field)(*item, field_index).map(ItemRef::Immutable) + } + } + } + + fn into_writable<T: Clone + 'static>(self) -> OwnedOrRefMut<'item, T> + { + match self { + ItemRef::Mutable(item) => OwnedOrRefMut::Ref( + (*item) + .downcast_mut::<T>() + .expect("Cannot downcast: wrong item type"), + ), + ItemRef::Immutable(item) => OwnedOrRefMut::Owned( + (*item) + .downcast_ref::<T>() + .expect("Cannot downcast: wrong item type") + .clone(), + ), + } + } +} + +impl AsRef<dyn Any> for ItemRef<'_> +{ + fn as_ref(&self) -> &dyn Any + { + match self { + Self::Mutable(item) => &**item, + Self::Immutable(item) => *item, + } + } +} + +#[derive(Debug)] +pub enum OwnedOrRefMut<'a, Value> +{ + Ref(&'a mut Value), + Owned(Value), +} + +impl<Value> Deref for OwnedOrRefMut<'_, Value> +{ + type Target = Value; + + fn deref(&self) -> &Self::Target + { + match self { + Self::Ref(value) => *value, + Self::Owned(value) => value, + } + } +} + +impl<Value> DerefMut for OwnedOrRefMut<'_, Value> +{ + fn deref_mut(&mut self) -> &mut Self::Target + { + match self { + Self::Ref(value) => *value, + Self::Owned(value) => value, + } + } +} + +fn create_item_title_widget( + frame: &dear_imgui_bindings::Ui, + item_title: &str, + item_type: &ItemType, + item_type_name: Option<&str>, +) +{ + if !matches!(item_type, ItemType::Reflected(TypeReflection::Reference(_))) { + frame.text(&item_title); + + if let Some(item_type_name) = item_type_name { + if frame.is_item_hovered() { + frame.tooltip_text(item_type_name); + } + } + } +} + +fn add_item_to_frame<'a>( + frame: &dear_imgui_bindings::Ui, + mut item: ItemRef<'_>, + data_changed: &mut bool, + ItemInfo { + item_title, + item_tag, + item_type_name, + item_type, + item_is_read_only, + }: ItemInfo<'a>, + prev_item_tags: &[&'a str], +) +{ + let _disabled = frame.begin_disabled_with_cond( + !matches!( + item_type, + ItemType::Reflected( + TypeReflection::Struct(_) + | TypeReflection::Enum(EnumReflection { is_unit_only: false, .. }) + | TypeReflection::Array(_) + | TypeReflection::Slice(_) + ) + ) && item_is_read_only, + ); + + match item_type { + ItemType::Reflected(TypeReflection::Struct(struct_ty)) => { + create_struct_widgets( + frame, + &mut item, + data_changed, + item_tag, + item_is_read_only, + struct_ty, + prev_item_tags, + ); + } + ItemType::Reflected(TypeReflection::Enum(enum_type)) => { + create_enum_widgets( + frame, + &mut item, + data_changed, + item_tag, + item_is_read_only, + enum_type, + prev_item_tags, + ); + } + ItemType::Reflected(TypeReflection::Literal(literal_reflection)) => { + match literal_reflection.ty { + LiteralType::U8 => create_scalar_item_input::<u8>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::I8 => create_scalar_item_input::<i8>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::U16 => create_scalar_item_input::<u16>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::I16 => create_scalar_item_input::<i16>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::U32 => create_scalar_item_input::<u32>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::I32 => create_scalar_item_input::<i32>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::U64 => create_scalar_item_input::<u64>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::I64 => create_scalar_item_input::<i64>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::F32 => create_scalar_item_input::<f32>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::F64 => create_scalar_item_input::<f64>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::Usize => create_scalar_item_input::<usize>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::Isize => create_scalar_item_input::<isize>( + frame, + &mut item, + data_changed, + &item_tag, + &prev_item_tags, + ), + LiteralType::U128 => { + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_mut::<u128>() else { + unreachable!(); + }; + + item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<u128>() else { + unreachable!(); + }; + + &mut item.clone() + } + }; + + frame.text(item.to_string()); + } + LiteralType::I128 => { + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_mut::<i128>() else { + unreachable!(); + }; + + item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<i128>() else { + unreachable!(); + }; + + &mut item.clone() + } + }; + + frame.text(item.to_string()); + } + LiteralType::Bool => { + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_mut::<bool>() else { + unreachable!(); + }; + + item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<bool>() else { + unreachable!(); + }; + + &mut item.clone() + } + }; + + if frame.checkbox( + create_item_label(&item_tag, "value_input", &prev_item_tags), + item, + ) { + *data_changed = true; + } + } + LiteralType::Str => { + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_ref::<&'static str>() + else { + unreachable!(); + }; + + *item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<&'static str>() + else { + unreachable!(); + }; + + *item + } + }; + + frame.text(item); + } + _ => unimplemented!(), + } + } + ItemType::Reflected(TypeReflection::Array(array_type)) => { + let mut prev_item_tags = prev_item_tags.to_vec(); + + prev_item_tags.push(item_tag); + + for array_item_index in 0..array_type.length { + let array_item_name = array_item_index.to_string(); + + let Ok(item_item) = (match &mut item { + ItemRef::Mutable(item) => { + (array_type.try_get_item_mut)(*item, array_item_index) + .map(ItemRef::Mutable) + } + ItemRef::Immutable(item) => { + (array_type.try_get_item)(*item, array_item_index) + .map(ItemRef::Immutable) + } + }) else { + unreachable!(); + }; + + create_item_title_widget( + frame, + &array_item_name, + &ItemType::Reflected(array_type.item_type), + Some(array_type.item_type_name()), + ); + + let array_item_type = ItemType::Reflected(array_type.item_type); + + let _token = array_item_type.indent_or_same_line(frame); + + add_item_to_frame( + frame, + item_item, + data_changed, + ItemInfo { + item_title: array_item_name.as_ref(), + item_tag: array_item_name.as_ref(), + item_type_name: Some(array_type.item_type_name()), + item_type: array_item_type, + item_is_read_only, + }, + &prev_item_tags, + ); + } + } + ItemType::Reflected(TypeReflection::Slice(slice_type)) => { + let mut prev_item_tags = prev_item_tags.to_vec(); + + prev_item_tags.push(item_tag); + + let Some(len) = (slice_type.try_get_len)(item.as_ref()) else { + unreachable!(); + }; + + for index in 0..len { + let item_name = index.to_string(); + + let Ok(item_item) = (slice_type.try_get_item)(item.as_ref(), index) + else { + unreachable!(); + }; + + let mut slice_item_changed = false; + + create_item_title_widget( + frame, + &item_name, + &ItemType::Reflected(slice_type.item_type), + Some(slice_type.item_type_name()), + ); + + let slice_item_type = ItemType::Reflected(slice_type.item_type); + + let _token = slice_item_type.indent_or_same_line(frame); + + add_item_to_frame( + frame, + ItemRef::Immutable(item_item), + &mut slice_item_changed, + ItemInfo { + item_title: &item_name, + item_tag: &item_name, + item_type_name: Some(slice_type.item_type_name()), + item_type: slice_item_type, + item_is_read_only: true, + }, + &prev_item_tags, + ); + + assert!(!slice_item_changed); + } + } + ItemType::Reflected(TypeReflection::Reference(ref_type)) => { + let mut derefed_changed = false; + + let Some(derefed_item) = (ref_type.try_deref)(item.as_ref()) else { + unreachable!(); + }; + + create_item_title_widget( + frame, + item_title, + &ItemType::Reflected(ref_type.ty), + item_type_name, + ); + + let ref_item_type = ItemType::Reflected(ref_type.ty); + + let _token = ref_item_type.indent_or_same_line(frame); + + add_item_to_frame( + frame, + ItemRef::Immutable(derefed_item), + &mut derefed_changed, + ItemInfo { + item_title, + item_tag: "derefed".into(), + item_type_name, + item_type: ref_item_type, + item_is_read_only: true, + }, + prev_item_tags, + ); + + assert!(!derefed_changed); + } + ItemType::String => { + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_mut::<String>() else { + unreachable!(); + }; + + item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<String>() else { + unreachable!(); + }; + + &mut item.clone() + } + }; + + if frame + .input_text( + create_item_label(&item_tag, "value_input", &prev_item_tags), + item, + ) + .build() + { + *data_changed = true; + } + } + ItemType::CowStr => { + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_mut::<Cow<'static, str>>() else { + unreachable!(); + }; + + item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<Cow<'static, str>>() else { + unreachable!(); + }; + + &mut item.clone() + } + }; + + if frame + .input_text( + create_item_label(&item_tag, "value_input", &prev_item_tags), + item.to_mut(), + ) + .build() + { + *data_changed = true; + } + } + ItemType::Color(ColorItemType::Rgb, LiteralType::F32) => { + let mut item = item.into_writable::<Rgb<f32>>(); + + let mut scratch = [item.r, item.g, item.b]; + + if frame + .color_edit3_config( + create_item_label(&item_tag, "value_input", &prev_item_tags), + &mut scratch, + ) + .display_mode(dear_imgui_bindings::ColorDisplayMode::Hex) + .build() + { + let [new_r, new_g, new_b] = scratch; + + *item = Rgb { r: new_r, g: new_g, b: new_b }; + + *data_changed = true; + } + } + ItemType::Color(ColorItemType::Rgb, LiteralType::U8) => { + let mut item = item.into_writable::<Rgb<u8>>(); + + let mut scratch = [ + item.r as f32 / 255.0, + item.g as f32 / 255.0, + item.b as f32 / 255.0, + ]; + + if frame + .color_edit3_config( + create_item_label(&item_tag, "value_input", &prev_item_tags), + &mut scratch, + ) + .display_mode(dear_imgui_bindings::ColorDisplayMode::Hex) + .build() + { + let [new_r, new_g, new_b] = scratch; + + *item = Rgb { + r: (new_r * 255.0) as u8, + g: (new_g * 255.0) as u8, + b: (new_b * 255.0) as u8, + }; + + *data_changed = true; + } + } + ItemType::Color(ColorItemType::Rgba, LiteralType::F32) => { + let mut item = item.into_writable::<Rgba<f32>>(); + + let mut scratch = [item.r, item.g, item.b, item.a]; + + if frame + .color_edit4_config( + create_item_label(&item_tag, "value_input", &prev_item_tags), + &mut scratch, + ) + .display_mode(dear_imgui_bindings::ColorDisplayMode::Hex) + .build() + { + let [new_r, new_g, new_b, new_a] = scratch; + + *item = Rgba { + r: new_r, + g: new_g, + b: new_b, + a: new_a, + }; + + *data_changed = true; + } + } + ItemType::Color(ColorItemType::Rgba, LiteralType::U8) => { + let mut item = item.into_writable::<Rgba<u8>>(); + + let mut scratch = [ + item.r as f32 / 255.0, + item.g as f32 / 255.0, + item.b as f32 / 255.0, + item.a as f32 / 255.0, + ]; + + if frame + .color_edit4_config( + create_item_label(&item_tag, "value_input", &prev_item_tags), + &mut scratch, + ) + .display_mode(dear_imgui_bindings::ColorDisplayMode::Hex) + .build() + { + let [new_r, new_g, new_b, new_a] = scratch; + + *item = Rgba { + r: (new_r * 255.0) as u8, + g: (new_g * 255.0) as u8, + b: (new_b * 255.0) as u8, + a: (new_a * 255.0) as u8, + }; + + *data_changed = true; + } + } + ItemType::Color(ColorItemType::Rgb, _) => unreachable!(), + ItemType::Color(ColorItemType::Rgba, _) => unreachable!(), + ItemType::Reflected(_) => unimplemented!(), + } +} + +fn create_scalar_item_input<Scalar>( + frame: &dear_imgui_bindings::Ui, + item: &mut ItemRef<'_>, + data_changed: &mut bool, + item_tag: &str, + prev_item_tags: &[&str], +) where + Scalar: dear_imgui_bindings::internal::DataTypeKind + Clone + 'static, +{ + let item = match item { + ItemRef::Mutable(item) => { + let Some(item) = (*item).downcast_mut::<Scalar>() else { + unreachable!(); + }; + + item + } + ItemRef::Immutable(item) => { + let Some(item) = (*item).downcast_ref::<Scalar>() else { + unreachable!(); + }; + + &mut item.clone() + } + }; + + if frame + .input_scalar( + create_item_label(item_tag, "value_input", &prev_item_tags), + item, + ) + .build() + { + *data_changed = true; + } +} + +fn item_layout_table<'frame>( + frame: &'frame dear_imgui_bindings::Ui, + prev_item_tags: &[&str], +) -> dear_imgui_bindings::TableBuilder<'frame> +{ + frame + .table(create_item_label("item_layout", "table", &prev_item_tags)) + .headers(false) + .sizing_policy(dear_imgui_bindings::TableSizingPolicy::StretchSame) + .columns([ + dear_imgui_bindings::TableColumnSetup::new("a"), + dear_imgui_bindings::TableColumnSetup::new("b").stretch_weight(2.0), + ]) +} + +fn create_struct_widgets( + frame: &dear_imgui_bindings::Ui, + item: &mut ItemRef<'_>, + data_changed: &mut bool, + item_tag: &str, + item_is_read_only: bool, + struct_ty: &StructReflection, + prev_item_tags: &[&str], +) +{ + let mut prev_item_tags = prev_item_tags.to_vec(); + + prev_item_tags.push(item_tag.as_ref()); + + let struct_fields = + struct_ty + .fields + .iter() + .enumerate() + .filter_map(|(field_index, field)| { + let field_item_type = + get_item_type(field.type_reflection(), field.type_id)?; + + Some((field_index, field, field_item_type)) + }); + + item_layout_table(frame, &prev_item_tags).build(|frame| { + for (field_index, field, field_item_type) in struct_fields + .clone() + .filter(|(.., field_item_type)| !field_item_type.spans_multiple_rows()) + { + frame.table_next_row(); + frame.table_next_column(); + + let field_name = field + .name + .map(Cow::Borrowed) + .unwrap_or_else(|| field_index.to_string().into()); + + let Ok(field_item) = item.get_struct_field(struct_ty, field_index) else { + unreachable!(); + }; + + create_item_title_widget( + frame, + &field_name, + &field_item_type, + Some(field.type_name()), + ); + + frame.table_next_column(); + + add_item_to_frame( + frame, + field_item, + data_changed, + ItemInfo { + item_title: field_name.as_ref(), + item_tag: field_name.as_ref(), + item_type_name: Some(field.type_name()), + item_type: field_item_type, + item_is_read_only: item_is_read_only + || matches!( + field.visibility, + Visibility::Private | Visibility::PubScoped(_) + ), + }, + &prev_item_tags, + ); + } + }); + + for (field_index, field, field_item_type) in struct_fields + .filter(|(.., field_item_type)| field_item_type.spans_multiple_rows()) + { + let field_name = field + .name + .map(Cow::Borrowed) + .unwrap_or_else(|| field_index.to_string().into()); + + let Ok(field_item) = item.get_struct_field(struct_ty, field_index) else { + unreachable!(); + }; + + create_item_title_widget( + frame, + &field_name, + &field_item_type, + Some(field.type_name()), + ); + + let _token = frame.begin_indent(); + + add_item_to_frame( + frame, + field_item, + data_changed, + ItemInfo { + item_title: field_name.as_ref(), + item_tag: field_name.as_ref(), + item_type_name: Some(field.type_name()), + item_type: field_item_type, + item_is_read_only: item_is_read_only + || matches!( + field.visibility, + Visibility::Private | Visibility::PubScoped(_) + ), + }, + &prev_item_tags, + ); + } +} + +fn create_enum_widgets( + frame: &dear_imgui_bindings::Ui, + item: &mut ItemRef<'_>, + data_changed: &mut bool, + item_tag: &str, + item_is_read_only: bool, + enum_type: &EnumReflection, + prev_item_tags: &[&str], +) +{ + let Some(mut curr_variant_index) = (enum_type.get_variant_index)(item.as_ref()) + else { + unreachable!(); + }; + + if create_combo_box( + frame, + create_item_label(&item_tag, "variant_select", &prev_item_tags), + &mut curr_variant_index, + enum_type.variants, + |variant| { + let disabled = variant.fields.as_ref().and_then(|fields| { + fields.fields().iter().find_map(|field| { + let field_name = match field.name { + Some(field_name) => Either::A(field_name), + None => Either::B(field.index), + }; + + let Some(field_type) = field.type_reflection() else { + return Some((field_name, "has no type reflection")); + }; + + if !field_type.has_default_value() { + return Some((field_name, "has no default value")); + } + + None + }) + }); + + ComboBoxItem { + label: variant.name.into(), + disabled: disabled.is_some(), + hover_tooltip: disabled.map(|(bad_field_name, bad_field_reason)| { + format!( + "Variant cannot be selected since field {} {}", + bad_field_name, bad_field_reason + ) + .into() + }), + } + }, + ) { + 'used: { + let ItemRef::Mutable(item) = item else { + break 'used; + }; + + let new_variant = &enum_type.variants[curr_variant_index]; + + let Ok(()) = (new_variant.try_write_new_to)( + *item, + &mut new_variant + .fields + .iter() + .map(|fields| fields.fields()) + .flatten() + .map(|field| { + let Some(field_type) = field.type_reflection() else { + // Variants with any field that is missing type reflection is + // disabled so that the user cannot select it + unreachable!(); + }; + + let Some(default_value) = field_type.default_value() else { + unreachable!(); + }; + + default_value + }), + ) else { + unreachable!(); + }; + + *data_changed = true; + } + } + + let mut prev_item_tags = prev_item_tags.to_vec(); + + prev_item_tags.push(item_tag); + + let curr_variant = &enum_type.variants[curr_variant_index]; + + let Some(curr_variant_fields) = &curr_variant.fields else { + return; + }; + + let variant_fields = curr_variant_fields.fields().iter().enumerate().filter_map( + |(field_index, field)| { + let field_item_type = get_item_type(field.type_reflection(), field.type_id)?; + + Some((field_index, field, field_item_type)) + }, + ); + + let variant_field_cnt = variant_fields.clone().count(); + + item_layout_table(frame, &prev_item_tags).build(|_| { + for (field_index, field, field_item_type) in variant_fields + .clone() + .filter(|(.., field_item_type)| !field_item_type.spans_multiple_rows()) + { + frame.table_next_row(); + frame.table_next_column(); + + let field_name: Cow<str> = match field.name { + Some(field_name) => field_name.into(), + None => field_index.to_string().into(), + }; + + let Ok(field_item) = item.get_enum_variant_field(curr_variant, field_index) + else { + unreachable!(); + }; + + if variant_field_cnt != 1 || field.name.is_some() { + create_item_title_widget( + frame, + &field_name, + &field_item_type, + Some(field.type_name()), + ); + + frame.table_next_column(); + } + + add_item_to_frame( + frame, + field_item, + data_changed, + ItemInfo { + item_title: field_name.as_ref(), + item_tag: field_name.as_ref(), + item_type_name: Some(field.type_name()), + item_type: field_item_type, + item_is_read_only: item_is_read_only, + }, + &prev_item_tags, + ); + } + }); + + for (field_index, field, field_item_type) in variant_fields + .filter(|(.., field_item_type)| field_item_type.spans_multiple_rows()) + { + let field_name: Cow<str> = match field.name { + Some(field_name) => field_name.into(), + None => field_index.to_string().into(), + }; + + let Ok(field_item) = item.get_enum_variant_field(curr_variant, field_index) + else { + unreachable!(); + }; + + if variant_field_cnt != 1 || field.name.is_some() { + create_item_title_widget( + frame, + &field_name, + &field_item_type, + Some(field.type_name()), + ); + + let _token = frame.begin_indent(); + } + + add_item_to_frame( + frame, + field_item, + data_changed, + ItemInfo { + item_title: field_name.as_ref(), + item_tag: field_name.as_ref(), + item_type_name: Some(field.type_name()), + item_type: field_item_type, + item_is_read_only: item_is_read_only, + }, + &prev_item_tags, + ); + } +} + +fn create_item_label(item_tag: &str, value_name: &str, prev_item_tags: &[&str]) + -> String +{ + let mut item_label = String::with_capacity( + 2 + item_tag.len() + + prev_item_tags.len() + + prev_item_tags.iter().max().unwrap_or(&"".into()).len(), + ); + + item_label.push_str("##"); + + for prev_item_tag in prev_item_tags { + item_label.push('/'); + item_label.push_str(prev_item_tag); + } + + item_label.push('/'); + item_label.push_str(item_tag); + item_label.push(':'); + item_label.push_str(value_name); + + item_label +} + +fn get_whole_type_is_user_editable( + ty: Option<&'static TypeReflection>, + type_id: TypeId, +) -> bool +{ + let Some(item_type) = get_item_type(ty, type_id) else { + return false; + }; + + match item_type { + ItemType::Reflected(TypeReflection::Struct(struct_ty)) => { + for field in struct_ty.fields { + if matches!( + field.visibility, + Visibility::Private | Visibility::PubScoped(_) + ) { + continue; + } + + if !get_whole_type_is_user_editable( + field.type_reflection(), + field.type_id, + ) { + return false; + } + } + + true + } + ItemType::Reflected(TypeReflection::Enum(enum_ty)) => { + enum_ty.variants.iter().any(|variant| { + for field in variant.fields.iter().flat_map(|fields| fields.fields()) { + if !get_whole_type_is_user_editable( + field.type_reflection(), + field.type_id, + ) { + return false; + } + } + + true + }) + } + ItemType::Reflected( + TypeReflection::Slice(_) + | TypeReflection::Array(_) + | TypeReflection::Literal(_), + ) + | ItemType::String + | ItemType::CowStr + | ItemType::Color(..) => true, + ItemType::Reflected(_) => unimplemented!(), + } +} + +struct ComboBoxItem<'b> +{ + label: Cow<'b, str>, + disabled: bool, + hover_tooltip: Option<Cow<'b, str>>, +} + +fn create_combo_box<Item, ItemFn>( + frame: &dear_imgui_bindings::Ui, + label: impl AsRef<str>, + current_item: &mut usize, + items: &[Item], + item_fn: ItemFn, +) -> bool +where + for<'b> ItemFn: Fn(&'b Item) -> ComboBoxItem<'b>, +{ + let item_fn = &item_fn; + + let mut result = false; + + let preview_label = items.get(*current_item).map(|item| item_fn(item).label); + + if let Some(combo_token) = frame.begin_combo( + label, + preview_label + .as_ref() + .map(|preview_label| preview_label.as_ref()) + .unwrap_or(""), + ) { + for (idx, item) in items.iter().enumerate() { + let is_selected = idx == *current_item; + + if is_selected { + frame.set_item_default_focus(); + } + + let ComboBoxItem { + label: item_label, + disabled: item_disabled, + hover_tooltip: item_hover_tooltip, + } = item_fn(item); + + let disabled_token = frame.begin_disabled_with_cond(item_disabled); + + let clicked = frame.selectable(item_label.as_ref()); + + if clicked { + *current_item = idx; + result = true; + } + + disabled_token.end(); + + if let Some(item_hover_tooltip) = item_hover_tooltip { + if frame.is_item_hovered_with_flags( + dear_imgui_bindings::ItemHoveredFlags::ALLOW_WHEN_DISABLED, + ) { + frame.tooltip_text(item_hover_tooltip.as_ref()); + } + } + } + + combo_token.end(); + } + + result +} + +struct ListBoxItem<'b> +{ + label: Cow<'b, str>, + disabled: bool, + hover_tooltip: Option<Cow<'b, str>>, +} + +trait ListBoxExt +{ + fn build_extended<Item, ItemFn>( + self, + ui: &dear_imgui_bindings::Ui, + current_item: &mut i32, + items: &[Item], + item_fn: &ItemFn, + ) -> bool + where + for<'b> ItemFn: Fn(&'b Item) -> ListBoxItem<'b>; +} + +impl<Label> ListBoxExt for dear_imgui_bindings::ListBox<Label> +where + Label: AsRef<str>, +{ + fn build_extended<Item, ItemFn>( + self, + ui: &dear_imgui_bindings::Ui, + current_item: &mut i32, + items: &[Item], + item_fn: &ItemFn, + ) -> bool + where + for<'b> ItemFn: Fn(&'b Item) -> ListBoxItem<'b>, + { + let mut result = false; + + let lb = self; + + if let Some(_cb) = lb.begin(ui) { + for (idx, item) in items.iter().enumerate() { + if idx > i32::MAX as usize { + break; + } + + let idx_i32 = idx as i32; + + let ListBoxItem { + label: item_label, + disabled: item_disabled, + hover_tooltip: item_hover_tooltip, + } = item_fn(item); + + let is_selected = idx_i32 == *current_item; + + let disabled_token = ui.begin_disabled_with_cond(item_disabled); + + if ui + .selectable_config(&item_label) + .selected(is_selected) + .build() + { + *current_item = idx_i32; + result = true; + } + + disabled_token.end(); + + if let Some(item_hover_tooltip) = item_hover_tooltip { + if ui.is_item_hovered_with_flags( + dear_imgui_bindings::ItemHoveredFlags::ALLOW_WHEN_DISABLED, + ) { + ui.tooltip_text(item_hover_tooltip.as_ref()); + } + } + } + } + + result + } +} + +fn create_entity_title(ent_handle: &EntityHandle) -> String +{ + let ent_name = ent_handle.get::<EntityName>(); + + format!( + "{} {}", + ent_name + .as_ref() + .map(|ent_name| ent_name.name.as_ref()) + .unwrap_or("<unnamed>"), + ent_handle.uid() + ) +} + +struct Textures +{ + despawn_icon_tex_id: dear_imgui_bindings::ManagedTextureId, + warning_icon_tex_id: dear_imgui_bindings::ManagedTextureId, + edit_icon_tex_id: dear_imgui_bindings::ManagedTextureId, +} + +impl Textures +{ + fn new(dear_imgui_context: &mut DearImguiContext) -> Self + { + let despawn_icon_tex_id = create_texture( + dear_imgui_context, + Image::from_reader( + Cursor::new(include_bytes!("../../../res/ui/delete.png")), + ImageFormat::Png, + ) + .unwrap(), + ); + + let warning_icon_tex_id = create_texture( + dear_imgui_context, + Image::from_reader( + Cursor::new(include_bytes!("../../../res/ui/warning.png")), + ImageFormat::Png, + ) + .unwrap(), + ); + + let edit_icon_tex_id = create_texture( + dear_imgui_context, + Image::from_reader( + Cursor::new(include_bytes!("../../../res/ui/edit.png")), + ImageFormat::Png, + ) + .unwrap(), + ); + + Self { + despawn_icon_tex_id, + warning_icon_tex_id, + edit_icon_tex_id, + } + } +} + +#[derive(Debug)] +struct AddComponentPopupState +{ + popup_name: String, + target_entity_id: Uid, + search_text: String, + searched_components: Vec<(Uid, ComponentInfo, ComponentUserCreatable)>, + searchable_components: Vec<(Uid, ComponentInfo, ComponentUserCreatable)>, + selected_search_result: i32, + new_component: Option<(Box<dyn Any>, ComponentInfo, Uid)>, +} + +#[derive(Debug)] +struct RenameEntityPopupState +{ + popup_name: String, + target_entity_id: Uid, + new_entity_name: String, +} + +#[derive(Debug)] +enum PopupState +{ + AddComponent(AddComponentPopupState), + RenameEntity(RenameEntityPopupState), +} |
