Skip to content

Commit

Permalink
Merge pull request #1 from Coffee-Nerd/development
Browse files Browse the repository at this point in the history
Merge changes from development branch to main
  • Loading branch information
Coffee-Nerd authored Mar 31, 2024
2 parents eeffd49 + be497b9 commit fe4b0bb
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 36 deletions.
88 changes: 70 additions & 18 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ pub mod functions;
mod miniwindow;
mod styles;
pub mod telnet;
use crate::app::functions::init_lua;
use crate::app::telnet::TelnetClient;
use egui::Color32;
use egui::TextBuffer;
use miniwindow::WindowResizeTest;
use mlua::Lua;
use mlua::{Function, Lua};

Check failure on line 12 in src/app.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused import: `Function`

Check warning on line 12 in src/app.rs

View workflow job for this annotation

GitHub Actions / Check

unused import: `Function`

Check warning on line 12 in src/app.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `Function`
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::Instant;
#[derive(serde::Deserialize, serde::Serialize, Default)]
#[serde(default)]
Expand All @@ -33,30 +38,28 @@ pub struct TemplateApp {
last_update_time: Option<Instant>,
show_lua_execution_window: RefCell<bool>,
#[serde(skip)]
lua: Lua,
lua: Option<Lua>,
lua_code: String,
lua_output_buffer: Arc<Mutex<String>>,
}

impl TemplateApp {
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
println!("Creating new TemplateApp instance");
// Set the custom style
let style = styles::default_style(); // Use the default style function
let style = styles::default_style();
cc.egui_ctx.set_style(style);

// Set the custom font
let font = styles::custom_font(); // Use the custom font function
let font = styles::custom_font();
cc.egui_ctx.set_fonts(font);

// Initialize the rest of the application
if let Some(storage) = cc.storage {
return eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default();
}
Self {
// Create a new TemplateApp instance
let app = TemplateApp {
label: "Hello World!".to_owned(),
value: 2.7,
window_resize_test: WindowResizeTest::new(),
telnet_client: telnet::TelnetClient::new(),
show_connection_prompt: RefCell::new(false), // Initialize
show_connection_prompt: RefCell::new(false),
ip_address: "127.0.0.1".to_owned(),
port: 23,
command: String::new(),
Expand All @@ -68,9 +71,17 @@ impl TemplateApp {
frame_durations: VecDeque::with_capacity(10),
last_update_time: None,
show_lua_execution_window: RefCell::new(false),
lua: Lua::new(),
lua: None,
lua_code: String::new(),
lua_output_buffer: Arc::new(Mutex::new(String::new())),
};

// Initialize the rest, if needed
if let Some(storage) = cc.storage {
return eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default();
}

app
}
}

Expand All @@ -80,6 +91,17 @@ impl eframe::App for TemplateApp {
}

fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let telnet_client = Arc::new(Mutex::new(TelnetClient::new()));

// Create a new Lua instance
if self.lua.is_none() {
let lua = Lua::new();
if let Err(err) = init_lua(&lua, telnet_client.clone()) {
eprintln!("Failed to initialize Lua: {:?}", err);
panic!("Failed to initialize Lua");
}
self.lua = Some(lua);
}
let menus: &[(&str, Vec<(&str, Box<dyn Fn(&mut Self, &egui::Context)>)>)] = &[

Check failure on line 105 in src/app.rs

View workflow job for this annotation

GitHub Actions / Clippy

very complex type used. Consider factoring parts into `type` definitions
(
"File",
Expand All @@ -98,7 +120,6 @@ impl eframe::App for TemplateApp {
)],
),
];

egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
for &(menu_name, ref submenus) in menus {
Expand Down Expand Up @@ -158,12 +179,35 @@ impl eframe::App for TemplateApp {

ui.add_space(8.0);
if ui.button("Execute").clicked() {
// Execute the Lua code here using Lua interpreter
match self.lua.load(&self.lua_code).exec() {
Ok(_) => println!("Lua code executed successfully."),
Err(e) => println!("Error executing Lua code: {}", e),
if let Some(lua) = &self.lua {
// Wrap the Lua code in a function that captures the output of print statements
let modified_lua_code = format!(
"local old_print = print; \
local output = ''; \
print = function(...) old_print(...); output = output .. ... .. '\\n'; end; \
{} \
print = old_print; \
return output",
self.lua_code
);

match lua.load(&modified_lua_code).eval::<String>() {
Ok(output) => {
// Append the output to the Telnet client
self.telnet_client.append_text(&output, Color32::KHAKI);
}
Err(err) => {
// Handle error
let error_message = format!("Error executing Lua code: {}\n", err);
self.telnet_client.append_text(&error_message, Color32::RED);
}
}
} else {
// Handle the case where lua is not initialized
eprintln!("Lua instance is not initialized.");
}
}

});
}

Expand Down Expand Up @@ -251,7 +295,7 @@ impl eframe::App for TemplateApp {
}

if self.telnet_client.is_connected() {
if let Some(data) = self.telnet_client.read_nonblocking() {
if let Some(_data) = self.telnet_client.read_nonblocking() {
// Request a repaint for the next frame
// println!("Received data: {}", data.text());
}
Expand Down Expand Up @@ -280,6 +324,14 @@ impl eframe::App for TemplateApp {
}
ctx.request_repaint();
}
if let Ok(mut buffer) = self.lua_output_buffer.lock() {
if !buffer.is_empty() {
let output = buffer.take();

// Append the output to the TelnetClient's received data
self.telnet_client.append_text(&output, Color32::WHITE); // Assuming white as the default output color
}
}
self.window_resize_test.show(ctx);
self.telnet_client.show(ctx);
}
Expand Down
11 changes: 7 additions & 4 deletions src/app/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,18 @@ use egui::Color32;
use mlua::prelude::*;
use std::sync::{Arc, Mutex};

// Define a struct that holds a reference to TelnetClient
pub struct LuaFunctions {
telnet_client: Arc<Mutex<TelnetClient>>,
}

impl LuaFunctions {
// Method for the print function
pub fn print(&self, text: String) -> LuaResult<()> {
println!("this is being called");
let mut telnet_client = self.telnet_client.lock().unwrap();
telnet_client.append_text(&text, Color32::WHITE);
Ok(())
}

// Method for the color_print function
pub fn color_print(&self, (text, color): (String, String)) -> LuaResult<()> {
let color = match color.as_str() {
"red" => Color32::RED,
Expand All @@ -32,20 +30,25 @@ impl LuaFunctions {

// Function to initialize and expose the functions to Lua
pub fn init_lua(lua: &Lua, telnet_client: Arc<Mutex<TelnetClient>>) -> LuaResult<()> {
println!("Initializing Lua environment with custom print functions...");
println!("Lua instance address in init_lua: {:p}", lua);

let print_functions = LuaFunctions {
telnet_client: telnet_client.clone(),
};
let color_print_functions = LuaFunctions { telnet_client };

let globals = lua.globals();

let print_function = lua.create_function(move |_, text: String| print_functions.print(text))?;
globals.set("print", print_function)?;

let color_print_function = lua.create_function(move |_, args: (String, String)| {
color_print_functions.color_print(args)
})?;
globals.set("color_print", color_print_function)?;
println!("Custom color_print function set in Lua environment.");

println!("Lua environment initialized successfully.");

Ok(())
}
12 changes: 6 additions & 6 deletions src/app/styles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ use egui::{Color32, FontData, FontDefinitions, FontFamily, Stroke, Style};

pub fn default_style() -> Style {
let mut style = Style::default();
style.visuals.extreme_bg_color = Color32::from_rgb(45, 51, 59); // text box background
style.visuals.faint_bg_color = Color32::from_rgb(45, 51, 59);
style.visuals.extreme_bg_color = Color32::from_rgb(20, 21, 23); // text box background
style.visuals.faint_bg_color = Color32::from_rgb(45, 46, 48);
style.visuals.code_bg_color = Color32::from_rgb(45, 51, 59);
style.visuals.hyperlink_color = Color32::from_rgb(255, 0, 0);
style.visuals.window_fill = Color32::from_rgb(0, 0, 0); // menu bg, widget bg
style.visuals.panel_fill = Color32::from_rgb(10, 10, 10); // entire window bg
style.visuals.override_text_color = Some(Color32::from_rgb(173, 186, 199));
style.visuals.panel_fill = Color32::from_rgb(18, 18, 20); // entire window bg
style.visuals.override_text_color = Some(Color32::from_rgb(255, 255, 255));
style.visuals.button_frame = true;
style.visuals.collapsing_header_frame = true;
style.visuals.widgets.noninteractive.bg_fill = Color32::from_rgb(35, 39, 46);
style.visuals.widgets.noninteractive.fg_stroke =
Stroke::new(0., Color32::from_rgb(173, 186, 199));
style.visuals.widgets.noninteractive.fg_stroke = Stroke::new(0., Color32::from_rgb(45, 46, 48));
style.visuals.widgets.active.fg_stroke = Stroke::new(0., Color32::from_rgb(45, 46, 48));
style.visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
style.visuals.widgets.hovered.bg_fill = Color32::from_rgb(45, 51, 59);
style.visuals.widgets.active.bg_fill = Color32::from_rgb(45, 51, 59);
Expand Down
5 changes: 4 additions & 1 deletion src/app/telnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ impl TelnetClient {
}
}
pub fn append_text(&mut self, text: &str, color: Color32) {
// Append the text and color to the received_data vector
println!("Appending to Telnet: {}", text); // Debug print
self.received_data.push(vec![(text.to_string(), color)]);
// Log the data pushed to received_data
println!("Pushed to received_data: {:?}", self.received_data.last());
}

pub fn connect(&mut self, ip_address: &str, port: u16) -> Result<(), String> {
Expand Down Expand Up @@ -156,6 +158,7 @@ impl TelnetClient {

impl Default for TelnetClient {
fn default() -> Self {
println!("Creating default TelnetClient instance");
Self::new()
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@

mod app;

use app::functions::init_lua;
use app::telnet::TelnetClient;
use mlua::prelude::*;
use std::sync::{Arc, Mutex};
use lazy_static::lazy_static;
use mlua::prelude::*; // Use prelude to include Lua and LuaError
use std::sync::Mutex; // Add this line to use the TelnetClient struct

lazy_static! {
pub static ref TELNET_CLIENT: Mutex<TelnetClient> = Mutex::new(TelnetClient::new());
}

#[derive(Debug)]
struct CustomError(String);
Expand All @@ -29,10 +33,6 @@ impl std::error::Error for CustomError {}
fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

let lua = Lua::new();
let telnet_client = Arc::new(Mutex::new(TelnetClient::new()));
init_lua(&lua, telnet_client).map_err(CustomError::from)?;

let native_options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([400.0, 300.0])
Expand Down

0 comments on commit fe4b0bb

Please sign in to comment.