Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,21 @@ builtin-parser = ["dep:logos"]

[dependencies]
# This crate by itself doesn't use any bevy features, but `bevy_egui` (dep) uses "bevy_asset".
bevy = { version = "0.14.0", default-features = false, features = [] }
bevy_egui = "0.28.0"
bevy = { version = "0.16.0", default-features = false, features = ["bevy_log", "bevy_color"] }
bevy_reflect = "0.16.0"
bevy_egui = "0.34.1"
chrono = "0.4.31"
tracing-log = "0.2.0"
tracing-subscriber = "0.3.18"
web-time = "1.0.0"
winit = "0.30.5"

# builtin-parser features
logos = { version = "0.14.0", optional = true }
fuzzy-matcher = { version = "0.3.7", optional = true }

[dev-dependencies]
bevy = "0.14.0"
bevy = "0.16.0"

[lints]
clippy.useless_format = "allow"
Expand Down
21 changes: 9 additions & 12 deletions src/builtin_parser/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ use bevy::reflect::{
DynamicEnum, DynamicTuple, ReflectMut, TypeInfo, TypeRegistration, VariantInfo,
};

use crate::ui::COMMAND_RESULT_NAME;

use self::error::EvalError;
use self::member::{eval_member_expression, eval_path, Path};
use self::reflection::{object_to_dynamic_struct, CreateRegistration, IntoResource};
Expand Down Expand Up @@ -142,7 +140,7 @@ pub fn run(ast: Ast, world: &mut World) -> Result<(), ExecutionError> {
value => {
let value = value.try_format(span, world, &registrations)?;

info!(name: COMMAND_RESULT_NAME, "{}{value}", crate::ui::COMMAND_RESULT_PREFIX);
info!(name: crate::ui::COMMAND_RESULT_NAME, "{}{value}", crate::ui::COMMAND_RESULT_PREFIX);
}
}
}
Expand Down Expand Up @@ -332,7 +330,11 @@ fn eval_expression(
}?;

dynamic_tuple.insert_boxed(
element.value.into_inner().reflect(element.span, ty)?,
element
.value
.into_inner()
.reflect(element.span, ty)?
.into_partial_reflect(),
);
}

Expand Down Expand Up @@ -369,13 +371,9 @@ fn eval_expression(
.reflect_path_mut(resource.path.as_str())
.unwrap();

reflect.set(value_reflect).map_err(|value_reflect| {
EvalError::IncompatibleReflectTypes {
span,
expected: reflect.reflect_type_path().to_string(),
actual: value_reflect.reflect_type_path().to_string(),
}
})?;
reflect
.try_apply(value_reflect.as_partial_reflect())
.map_err(|apply_error| EvalError::ApplyError { apply_error, span })?;
}
}

Expand Down Expand Up @@ -441,7 +439,6 @@ fn eval_expression(
)?;
Ok(Value::StructTuple { name, tuple })
}

Expression::BinaryOp {
left,
operator,
Expand Down
2 changes: 1 addition & 1 deletion src/builtin_parser/runner/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::fmt::Debug;

use crate::builtin_parser::SpanExtension;
use bevy::ecs::world::World;
use bevy::log::warn;
use bevy::prelude::*;
use bevy::reflect::TypeRegistration;
use logos::Span;

Expand Down
15 changes: 15 additions & 0 deletions src/builtin_parser/runner/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::borrow::Cow;

use bevy::reflect::ApplyError;
use logos::Span;

use crate::builtin_parser::number::Number;
Expand Down Expand Up @@ -75,6 +76,10 @@ pub enum EvalError {
field_index: usize,
tuple_size: usize,
},
ApplyError {
apply_error: ApplyError,
span: Span,
},
}

impl EvalError {
Expand Down Expand Up @@ -106,6 +111,7 @@ impl EvalError {
E::InvalidOperation { span, .. } => vec![span.clone()],
E::IncorrectAccessOperation { span, .. } => vec![span.clone()],
E::FieldNotFoundInTuple { span, .. } => vec![span.clone()],
E::ApplyError { span, .. } => vec![span.clone()],
}
}
/// Returns all the hints for this error.
Expand Down Expand Up @@ -232,6 +238,15 @@ impl std::fmt::Display for EvalError {
f,
"Field {field_index} is out of bounds for tuple of size {tuple_size}"
),
E::ApplyError {
apply_error,
span: _,
} => {
write!(
f,
"Error while applying value (todo make this error better): {apply_error}"
)
}
}
}
}
Expand Down
13 changes: 7 additions & 6 deletions src/builtin_parser/runner/reflection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,16 @@ impl IntoResource {
}

pub fn object_to_dynamic_struct(
hashmap: HashMap<String, (Value, Span, &'static str)>,
_hashmap: HashMap<String, (Value, Span, &'static str)>,
) -> Result<DynamicStruct, EvalError> {
let mut dynamic_struct = DynamicStruct::default();
todo!()
// let mut dynamic_struct = DynamicStruct::default();

for (key, (value, span, reflect)) in hashmap {
dynamic_struct.insert_boxed(&key, value.reflect(span, reflect)?);
}
// for (key, (value, span, reflect)) in hashmap {
// dynamic_struct.insert_boxed(&key, value.reflect(span, reflect)?);
// }

Ok(dynamic_struct)
// Ok(dynamic_struct)
}

pub fn mut_dyn_reflect<'a>(
Expand Down
2 changes: 1 addition & 1 deletion src/builtin_parser/runner/stdlib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::builtin_parser::runner::environment::Variable;
use crate::register;
use bevy::ecs::world::World;
use bevy::log::info;
use bevy::prelude::*;
use bevy::reflect::TypeRegistration;
use std::cell::Ref;
use std::ops::Range;
Expand Down
2 changes: 1 addition & 1 deletion src/builtin_parser/runner/unique_rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl<T> UniqueRc<T> {
.into_inner()
}
}
impl<T: ?Sized + Clone> Clone for UniqueRc<T> {
impl<T: Clone> Clone for UniqueRc<T> {
fn clone(&self) -> Self {
let t = self.borrow_inner().clone().into_inner();

Expand Down
18 changes: 11 additions & 7 deletions src/builtin_parser/runner/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::unique_rc::WeakRef;

use bevy::ecs::world::World;
use bevy::reflect::{
DynamicStruct, DynamicTuple, GetPath, Reflect, ReflectRef, TypeInfo, TypeRegistration,
DynamicStruct, DynamicTuple, GetPath, PartialReflect, ReflectRef, TypeInfo, TypeRegistration,
VariantInfo, VariantType,
};

Expand Down Expand Up @@ -61,13 +61,15 @@ pub enum Value {
}

impl Value {
/// Converts this value into a [`Box<dyn Reflect>`].
/// Converts this value into a [`Box<dyn PartialReflect>`].
///
/// `ty` is used for type inference.
pub fn reflect(self, span: Span, ty: &str) -> Result<Box<dyn Reflect>, EvalError> {
pub fn reflect(self, span: Span, ty: &str) -> Result<Box<dyn PartialReflect>, EvalError> {
match self {
Value::None => Ok(Box::new(())),
Value::Number(number) => number.reflect(span, ty),
Value::Number(number) => number
.reflect(span, ty)
.map(PartialReflect::into_partial_reflect),
Value::Boolean(boolean) => Ok(Box::new(boolean)),
Value::String(string) => Ok(Box::new(string)),
Value::Reference(_reference) => Err(EvalError::CannotReflectReference(span)),
Expand Down Expand Up @@ -245,7 +247,7 @@ fn fancy_debug_print(

let reflect = dyn_reflect.reflect_path(resource.path.as_str()).unwrap();

fn debug_subprint(reflect: &dyn Reflect, indentation: usize) -> String {
fn debug_subprint(reflect: &dyn PartialReflect, indentation: usize) -> String {
let mut f = String::new();
let reflect_ref = reflect.reflect_ref();
let indentation_string = TAB.repeat(indentation);
Expand Down Expand Up @@ -311,9 +313,10 @@ fn fancy_debug_print(
VariantType::Unit => {}
}
}
ReflectRef::Value(_) => {
ReflectRef::Opaque(_) => {
f += &format!("{reflect:?}");
}
ReflectRef::Set(_) => todo!(),
}

f
Expand Down Expand Up @@ -343,6 +346,7 @@ fn fancy_debug_print(
ReflectRef::List(_) => todo!(),
ReflectRef::Array(_) => todo!(),
ReflectRef::Map(_) => todo!(),
ReflectRef::Set(_) => todo!(),
ReflectRef::Enum(set_variant_info) => {
// Print out the enum types
f += &format!("enum {} {{\n", set_variant_info.reflect_short_type_path());
Expand Down Expand Up @@ -401,7 +405,7 @@ fn fancy_debug_print(
VariantType::Unit => {}
}
}
ReflectRef::Value(value) => {
ReflectRef::Opaque(value) => {
f += &format!("{value:?}");
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use std::borrow::Cow;
use std::ops::Range;

use bevy::ecs::world::Command;
use bevy::prelude::*;

/// The command parser currently being used by the dev console.
Expand Down Expand Up @@ -168,6 +167,7 @@ impl Command for ExecuteCommand {
}
}

#[allow(missing_docs)]
#[derive(Resource, Default, Deref, DerefMut)]
#[cfg(feature = "completions")]
pub struct AutoCompletions(pub(crate) Vec<CompletionSuggestion>);
Expand Down
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ pub struct DevConsolePlugin;
impl Plugin for DevConsolePlugin {
fn build(&self, app: &mut App) {
if !app.is_plugin_added::<EguiPlugin>() {
app.add_plugins(EguiPlugin);
app.add_plugins(EguiPlugin {
enable_multipass_for_primary_context: false,
});
}

#[cfg(feature = "builtin-parser")]
Expand Down
13 changes: 6 additions & 7 deletions src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
//! Custom [LogPlugin](bevy::log::LogPlugin) functionality.

use bevy::log::{BoxedLayer, Level};
use bevy::log::tracing::Subscriber;
use bevy::prelude::*;
use bevy::utils::tracing::Subscriber;
use std::sync::mpsc;
use tracing_subscriber::field::Visit;
use tracing_subscriber::Layer;
use web_time::SystemTime;

/// A function that implements the log reading functionality for the
/// developer console via [`LogPlugin::custom_layer`](bevy::log::LogPlugin::custom_layer).
pub fn custom_log_layer(app: &mut App) -> Option<BoxedLayer> {
pub fn custom_log_layer(app: &mut App) -> Option<bevy::log::BoxedLayer> {
Some(Box::new(create_custom_log_layer(app)))
}

Expand Down Expand Up @@ -39,7 +38,7 @@ pub(crate) struct LogMessage {
pub target: &'static str,

/// The level of verbosity of the described span.
pub level: Level,
pub level: bevy::log::Level,

/// The name of the Rust module where the span occurred,
/// or `None` if this could not be determined.
Expand All @@ -62,7 +61,7 @@ fn transfer_log_events(
receiver: NonSend<CapturedLogEvents>,
mut log_events: EventWriter<LogMessage>,
) {
log_events.send_batch(receiver.0.try_iter());
log_events.write_batch(receiver.0.try_iter());
}

/// This struct temporarily stores [`LogMessage`]s before they are
Expand All @@ -76,7 +75,7 @@ struct LogCaptureLayer {
impl<S: Subscriber> Layer<S> for LogCaptureLayer {
fn on_event(
&self,
event: &bevy::utils::tracing::Event<'_>,
event: &bevy::log::tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut message = None;
Expand Down Expand Up @@ -104,7 +103,7 @@ struct LogEventVisitor<'a>(&'a mut Option<String>);
impl Visit for LogEventVisitor<'_> {
fn record_debug(
&mut self,
field: &bevy::utils::tracing::field::Field,
field: &bevy::log::tracing::field::Field,
value: &dyn std::fmt::Debug,
) {
// Only log out messages
Expand Down
21 changes: 11 additions & 10 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub const COMMAND_MESSAGE_NAME: &str = "console_command";
/// Identifier for log messages that show the result of a command.
pub const COMMAND_RESULT_NAME: &str = "console_result";

#[allow(missing_docs)]
#[derive(Default, Resource)]
pub struct ConsoleUiState {
/// Whether the console is open or not.
Expand Down Expand Up @@ -117,26 +118,26 @@ pub fn render_ui(
info!(name: COMMAND_MESSAGE_NAME, "{COMMAND_MESSAGE_PREFIX}{}", command.trim());
// Get the owned command string by replacing it with an empty string
let command = std::mem::take(command);
commands.add(ExecuteCommand(command));
commands.queue(ExecuteCommand(command));
}
}

if key.just_pressed(config.submit_key) {
submit_command(&mut state.command, commands);
}

completions::change_selected_completion(ui, state, &completions);
completions::change_selected_completion(ui, state, completions);

// A General rule when creating layouts in egui is to place elements which fill remaining space last.
// Since immediate mode ui can't predict the final sizes of widgets until they've already been drawn

// Thus we create a bottom panel first, where our text edit and submit button resides.
egui::TopBottomPanel::bottom("bottom panel")
.frame(egui::Frame::none().outer_margin(egui::Margin {
left: 5.0,
right: 5.0,
top: 5. + 6.,
bottom: 5.0,
.frame(egui::Frame::NONE.outer_margin(egui::Margin {
left: 5,
right: 5,
top: 5 + 6,
bottom: 5,
}))
.show_inside(ui, |ui| {
let text_edit_id = egui::Id::new("text_edit");
Expand Down Expand Up @@ -169,8 +170,8 @@ pub fn render_ui(
state,
ui,
commands,
&completions,
&config,
completions,
config,
);

// Each time we open the console, we want to set focus to the text edit control.
Expand All @@ -188,7 +189,7 @@ pub fn render_ui(
let mut command_index = 0;

for (id, (message, is_new)) in state.log.iter_mut().enumerate() {
add_log(ui, id, message, is_new, hints, &config, &mut command_index);
add_log(ui, id, message, is_new, hints, config, &mut command_index);
}
});
});
Expand Down
Loading
Loading