feat: handle spawning multiple windows

This commit is contained in:
Chance 2025-03-24 19:42:32 -04:00 committed by BitSyndicate
parent ae2316bb88
commit d26499823b
Signed by: bitsyndicate
GPG key ID: 443E4198D6BBA6DE
6 changed files with 61 additions and 123 deletions

View file

@ -12,7 +12,6 @@ crashreport = "1.0.1"
dirs-next = "2.0.0"
lazy_static.workspace = true
log = "0.4.22"
once_cell = "1.20.2"
parking_lot.workspace = true
regex = "1.11.1"
@ -24,6 +23,7 @@ winit = "0.30.8"
bytemuck = "1.21.0"
futures = "0.3.31"
cgmath = "0.18.0"
tracing = "0.1.41"
[profile.dev]

View file

@ -1,84 +0,0 @@
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::sync::Arc;
use colored::Colorize;
use log::{Level, Log, Metadata, Record};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
pub static LOGGER: Lazy<DynamicLogger> = Lazy::new(DynamicLogger::new);
// A logger that dynamically switches between file and stdout
pub struct DynamicLogger {
pub writer: Arc<Mutex<Box<dyn Write + Send>>>,
}
impl Default for DynamicLogger {
fn default() -> Self {
Self::new()
}
}
impl DynamicLogger {
pub fn new() -> Self {
Self {
writer: Arc::new(Mutex::new(Box::new(io::stdout()))),
}
}
pub fn write_to_file(&self, file_path: &str) {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(file_path)
.expect("Failed to open log file");
*self.writer.lock() = Box::new(file);
}
pub fn write_to_stdout(&self) {
*self.writer.lock() = Box::new(io::stdout());
}
fn colorize_level(level: Level) -> colored::ColoredString {
match level {
Level::Error => "ERROR".red(),
Level::Warn => "WARN".yellow(),
Level::Info => "INFO".green(),
Level::Debug => "DEBUG".blue(),
Level::Trace => "TRACE".cyan(),
}
}
}
impl Log for DynamicLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
let target = metadata.target();
let is_relevant_target = target.starts_with("wgpu")
|| target.starts_with("winit")
|| target.starts_with(env!("CARGO_PKG_NAME")); // Current crate name
is_relevant_target && metadata.level() <= Level::Debug
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let mut writer = self.writer.lock();
let level = Self::colorize_level(record.level()); // Apply coloring
writeln!(
writer,
"{} [{}] - {}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
level,
record.args()
)
.unwrap();
}
}
fn flush(&self) {
let mut writer = self.writer.lock();
writer.flush().unwrap();
}
}

View file

@ -1,5 +1,4 @@
pub mod ecs;
pub mod logger;
pub mod panic;
pub mod repl;
pub mod splash;

View file

@ -1,7 +1,7 @@
use std::sync::Arc;
use ctx::WgpuCtx;
use log::{debug, trace};
use tracing::{debug, error, info, trace, warn};
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ControlFlow;
@ -11,20 +11,20 @@ pub mod ctx;
#[derive(Default)]
pub struct App<'window> {
window: Option<Arc<Window>>,
window: Vec<Arc<Window>>,
ctx: Option<WgpuCtx<'window>>,
}
impl ApplicationHandler for App<'_> {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_none() {
if self.window.is_empty() {
let win_attr = Window::default_attributes().with_title("Zenyx");
let window = Arc::new(
event_loop
.create_window(win_attr)
.expect("create window err."),
);
self.window = Some(window.clone());
self.window.push(window.clone());
let wgpu_ctx = WgpuCtx::new_blocking(window.clone()).unwrap();
self.ctx = Some(wgpu_ctx)
}
@ -33,53 +33,77 @@ impl ApplicationHandler for App<'_> {
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: WindowId,
window_id: WindowId,
event: WindowEvent,
) {
match event {
WindowEvent::CloseRequested => {
event_loop.exit();
debug!("Window closed, exiting");
std::process::exit(0)
if let Some(index) = self.window.iter().position(|window| window.id() == window_id) {
let window = self.window.remove(index);
// how do i close a window :(
window.set_title("Dead window");
debug!("Window closed, exiting");
}
if self.window.is_empty() {
event_loop.exit();
}
}
WindowEvent::KeyboardInput { device_id, event, is_synthetic } => {
match event.physical_key {
winit::keyboard::PhysicalKey::Code(code) => {
if event.state.is_pressed() == false {
return;
}
if code == winit::keyboard::KeyCode::Escape {
// event_loop.exit();
debug!("Window closed, exiting");
WindowEvent::KeyboardInput {
device_id,
event,
is_synthetic,
} => match event.physical_key {
winit::keyboard::PhysicalKey::Code(code) => {
if event.state.is_pressed() == false {
return;
}
match code {
winit::keyboard::KeyCode::Space => {
debug!("Space key pressed");
if let Some(ctx) = &mut self.ctx {
match ctx.bg_color() {
wgpu::Color::WHITE => ctx.change_bg_color(wgpu::Color::BLACK),
wgpu::Color::BLACK => ctx.change_bg_color(wgpu::Color::WHITE),
_ => ctx.change_bg_color(wgpu::Color::WHITE),
}
}
// std::process::exit(0)
}
winit::keyboard::KeyCode::Escape => {
debug!("Escape key pressed, spawning new window");
let win_attr =
Window::default_attributes().with_title("Zenyx - New Window");
let new_window = Arc::new(
event_loop
.create_window(win_attr)
.expect("create window err."),
);
self.window.push(new_window.clone());
let wgpu_ctx = WgpuCtx::new_blocking(new_window.clone()).unwrap();
self.ctx = Some(wgpu_ctx);
}
_ => info!("Unimplemented keycode: {:?}", code),
}
}
_ => {}
}
}
},
WindowEvent::RedrawRequested => {
if let Some(ctx) = &mut self.ctx {
ctx.draw();
}
if let Some(window) = &self.window {
for window in &self.window {
if let Some(ctx) = &mut self.ctx {
ctx.draw();
}
window.request_redraw();
}
}
WindowEvent::Resized(size) => {
if let (Some(wgpu_ctx), Some(window)) = (&mut self.ctx, &self.window) {
wgpu_ctx.resize(size.into());
window.request_redraw();
let size_str: String = size.height.to_string() + "x" + &size.width.to_string();
//self.window.as_ref().unwrap().set_title(&format!("you reszed the window to
// {size_str}"));
debug!("Window resized to {:?}", size_str);
if let Some(window) = self.window.iter().find(|w| w.id() == window_id) {
if let Some(wgpu_ctx) = &mut self.ctx {
wgpu_ctx.resize(size.into());
window.request_redraw();
let size_str: String =
size.height.to_string() + "x" + &size.width.to_string();
debug!("Window resized to {:?}", size_str);
}
}
}
_ => trace!("Unhandled window event"),

View file

@ -5,7 +5,6 @@ use std::{
use chrono::Local;
use colored::Colorize;
use log::debug;
use parking_lot::Mutex;
use regex::Regex;
use rustyline::{
@ -13,9 +12,9 @@ use rustyline::{
Hinter, KeyEvent, RepeatCount, Validator, completion::Completer, error::ReadlineError,
highlight::Highlighter, hint::HistoryHinter, history::DefaultHistory,
};
use tracing::{debug, error, info, warn};
use super::handler::COMMAND_MANAGER;
use crate::core::logger::LOGGER;
struct CommandCompleter;
impl CommandCompleter {
@ -89,9 +88,9 @@ impl ConditionalEventHandler for BacktickEventHandler {
if *state { "ON".green() } else { "OFF".red() }
);
if *state {
LOGGER.write_to_stdout();
// LOGGER.write_to_stdout();
} else {
LOGGER.write_to_file("z.log");
// LOGGER.write_to_file("z.log");
}
*state = !*state;
Some(Cmd::Noop)

View file

@ -1,10 +1,10 @@
use core::{panic::set_panic_hook, repl::setup, splash, workspace};
use colored::Colorize;
use log::info;
use tokio::runtime;
#[allow(unused_imports)]
use tracing::{debug, error, info, warn};
use winit::event_loop::EventLoop;
pub mod core;
#[tokio::main(flavor = "current_thread")]