tirbofish/dropbear
main / crates / eucalyptus-editor / src / menu.rs · 21820 bytes
crates/eucalyptus-editor/src/menu.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use crate::editor::settings::editor::EditorSettingsWindow;
use anyhow::{Context, anyhow};
use dropbear_engine::{
DropbearWindowBuilder,
future::{FutureHandle, FutureQueue},
input::{Controller, Keyboard, Mouse},
scene::{Scene, SceneCommand},
};
use egui::{self, FontId, Frame, RichText, Ui};
use egui_toast::{ToastOptions, Toasts};
use eucalyptus_core::config::ProjectConfig;
use eucalyptus_core::states::PROJECT;
use git2::Repository;
use log::{self, debug};
use log_once::debug_once;
use parking_lot::RwLock;
use rfd::FileDialog;
use std::rc::Rc;
use std::sync::Arc;
use std::{fs, path::PathBuf};
use tokio::sync::watch;
use winit::window::WindowAttributes;
use winit::{
dpi::PhysicalPosition, event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode,
};
#[derive(Debug, Clone)]
pub enum ProjectProgress {
Step { progress: f32, message: String },
Error(String),
Done,
}
#[derive(Default)]
pub struct MainMenu {
scene_command: SceneCommand,
show_new_project: bool,
project_name: String,
project_domain: String,
project_path: Option<PathBuf>,
project_error: Option<Vec<String>>,
project_progress_rx: Option<watch::Receiver<ProjectProgress>>,
show_progress: bool,
progress: f32,
progress_message: String,
project_creation_handle: Option<FutureHandle>,
toast: Toasts,
is_in_file_dialogue: bool,
}
impl MainMenu {
pub fn new() -> Self {
Self {
show_progress: false,
toast: Toasts::new()
.anchor(egui::Align2::RIGHT_BOTTOM, (-10.0, -10.0))
.direction(egui::Direction::BottomUp),
..Default::default()
}
}
fn start_project_creation(&mut self, queue: Arc<FutureQueue>) {
let project_name = self.project_name.clone();
let project_path = self.project_path.clone();
let project_domain = self.project_domain.clone();
let (progress_tx, progress_rx) = watch::channel(ProjectProgress::Step {
progress: 0.0,
message: "Starting project creation...".to_string(),
});
self.project_progress_rx = Some(progress_rx);
self.show_progress = true;
self.progress = 0.0;
let handle = queue.push(async move {
let mut errors = Vec::new();
let folders = [
("gradle", 0.1, "Unpacking gradle template..."),
("setting_config", 0.2, "Setting gradle config..."),
("git", 0.3, "Initialising git repository..."),
("resources/models", 0.3, "Creating models folder..."),
("resources/shaders", 0.4, "Creating shaders folder..."),
("resources/textures", 0.5, "Creating textures folder..."),
("src2", 0.6, "Generating project config..."),
("resources/scenes", 0.7, "Creating scenes folder..."),
];
if let Some(path) = &project_path {
for (folder, progress, message) in folders {
let _ = progress_tx.send(ProjectProgress::Step {
progress,
message: message.to_string(),
});
let full_path = path.join(folder);
let result: anyhow::Result<()> = match folder {
"git" => {
log::debug!("Initialising git repository");
match Repository::init(path) {
Ok(_) => Ok(()),
Err(e) => {
if matches!(e.code(), git2::ErrorCode::Exists) {
log::warn!("Git repository already exists");
Ok(())
} else {
Err(anyhow!(e))
}
}
}
}
"src2" => {
log::debug!("Generating project config");
let mut config = ProjectConfig::new(project_name.clone(), path);
let _ = config.write_to_all();
let mut global = PROJECT.write();
*global = config;
Ok(())
}
"setting_config" => {
let project_root = path.clone();
let src_script_path =
project_root.join("src/commonMain/kotlin/Script.kt");
let domain_path = project_domain.clone().replace('.', "/");
let dest_script_path = project_root.join(format!(
"src/commonMain/kotlin/{}/{}/Script.kt",
domain_path,
project_name.to_lowercase()
));
if let Some(parent) = dest_script_path.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&src_script_path, &dest_script_path)?;
let mut content = fs::read_to_string(&dest_script_path)?;
let package_declaration = format!(
"package {}.{}\n\n",
project_domain.clone(),
project_name.clone().to_lowercase()
);
content = package_declaration + &content;
fs::write(&dest_script_path, content)?;
let build_gradle_path = project_root.join("build.gradle.kts");
let gradle_content = fs::read_to_string(&build_gradle_path)?;
let updated_gradle_content = gradle_content
.replace("domain", project_domain.clone().as_str())
.replace("projectExample", &project_name.to_lowercase());
fs::write(&build_gradle_path, updated_gradle_content)?;
Ok(())
}
"gradle" => {
log::debug!("Cloning gradle template from GitHub");
let url = "https://github.com/tirbofish/eucalyptus-gradle-template";
fs::create_dir_all(path)
.context("Failed to create project directory")?;
let temp_clone_path = path.with_file_name(format!(
"{}.clone_tmp",
path.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default()
));
Repository::clone(url, &temp_clone_path)?;
for entry in fs::read_dir(&temp_clone_path)? {
let entry = entry?;
let file_name = entry.file_name();
if file_name == ".git" {
continue;
}
let dest_path = path.join(file_name);
fs::rename(entry.path(), dest_path)?;
}
fs::remove_dir_all(&temp_clone_path)
.context("Failed to remove temporary clone directory")?;
log::debug!("Template cloned and .git removed successfully");
Ok(())
}
_ => {
log::debug!("Creating folder: {:?}", full_path);
if !full_path.exists() {
fs::create_dir_all(&full_path)
.map_err(|e| anyhow::anyhow!(e))
.map(|_| ())
} else {
log::warn!("{:?} already exists", full_path);
Ok(())
}
}
};
if let Err(e) = result {
let _ = progress_tx.send(ProjectProgress::Error(e.to_string()));
errors.push(e);
}
}
let _ = progress_tx.send(ProjectProgress::Step {
progress: 1.0,
message: "Finalising project...".to_string(),
});
if errors.is_empty() {
let _ = progress_tx.send(ProjectProgress::Done);
Ok(())
} else {
Err(anyhow!(
"Project creation failed with {} errors",
errors.len()
))
}
} else {
let _ =
progress_tx.send(ProjectProgress::Error("Project path not set".to_string()));
Err(anyhow!("Project path not set"))
}
});
self.project_creation_handle = Some(handle);
queue.poll();
debug!("Starting project creation");
}
}
impl Scene for MainMenu {
fn load(
&mut self,
_graphics: std::sync::Arc<dropbear_engine::graphics::SharedGraphicsContext>,
_ui: &mut Ui
) {
log::info!("Loaded main menu scene");
}
fn physics_update(
&mut self,
_dt: f32,
_graphics: std::sync::Arc<dropbear_engine::graphics::SharedGraphicsContext>,
_ui: &mut Ui,
) {
}
fn update(
&mut self,
_dt: f32,
_graphics: std::sync::Arc<dropbear_engine::graphics::SharedGraphicsContext>,
_ui: &mut Ui,
) {
}
fn render<'a>(
&mut self,
graphics: std::sync::Arc<dropbear_engine::graphics::SharedGraphicsContext>,
ui: &mut Ui,
) {
#[allow(clippy::collapsible_if)]
if let Some(handle) = self.project_creation_handle.as_ref() {
if let Some(result) = graphics
.future_queue
.exchange_owned_as::<anyhow::Result<()>>(handle)
{
self.project_creation_handle = None;
if let Err(e) = result {
log::error!("Project creation failed: {e}");
self.project_error
.get_or_insert_with(Vec::new)
.push(e.to_string());
} else {
log::info!("Project created successfully!");
self.show_new_project = false;
self.show_progress = false;
self.scene_command = SceneCommand::SwitchScene("editor".to_string());
}
}
}
if let Some(rx) = self.project_progress_rx.as_ref()
&& let Ok(true) = rx.has_changed()
{
let progress = rx.borrow().clone();
match progress {
ProjectProgress::Step { progress, message } => {
self.progress = progress;
self.progress_message = message;
}
ProjectProgress::Error(err) => {
self.project_error.get_or_insert_with(Vec::new).push(err);
}
ProjectProgress::Done => {}
}
}
let screen_size: (f32, f32) = (
graphics.window.inner_size().width as f32 - 100.0,
graphics.window.inner_size().height as f32 - 100.0,
);
let egui_ctx = ui.ctx().clone();
let mut local_open_project = false;
let mut local_select_project = false;
egui::CentralPanel::default()
.frame(Frame::new())
.show_inside(ui, |ui| {
ui.vertical_centered(|ui| {
ui.add_space(64.0);
ui.label(RichText::new("Eucalyptus").font(FontId::proportional(32.0)));
ui.add_space(40.0);
let button_size = egui::vec2(300.0, 60.0);
let is_busy =
self.is_in_file_dialogue || self.project_creation_handle.is_some();
if ui
.add_enabled(
!is_busy,
egui::Button::new("New Project").min_size(button_size),
)
.clicked()
{
log::debug!("Creating new project");
self.show_new_project = true;
}
ui.add_space(20.0);
if ui
.add_enabled(
!is_busy,
egui::Button::new("Open Project").min_size(button_size),
)
.clicked()
{
local_open_project = true;
}
ui.add_space(20.0);
if ui
.add_enabled(
!is_busy,
egui::Button::new("Settings").min_size(button_size),
)
.clicked()
{
debug!("Editor settings");
let window_data = DropbearWindowBuilder::new()
.with_attributes(
WindowAttributes::default()
.with_title("eucalyptus editor - settings"),
)
.add_scene_with_input(
Rc::new(RwLock::new(EditorSettingsWindow::new())),
"editor_settings",
)
.set_initial_scene("editor_settings")
.build();
self.scene_command = SceneCommand::RequestWindow(window_data);
debug!("Requested editor settings window");
}
ui.add_space(20.0);
if ui
.add_enabled(!is_busy, egui::Button::new("Quit").min_size(button_size))
.clicked()
{
self.scene_command = SceneCommand::Quit(None);
}
ui.add_space(20.0);
});
});
if local_open_project {
debug!("Opening project dialog");
self.is_in_file_dialogue = true;
if let Some(path) = FileDialog::new()
.add_filter("Eucalyptus Configuration Files", &["eucp"])
.pick_file()
{
log::debug!("Reading from {}", path.display());
match ProjectConfig::read_from(&path) {
Ok(config) => {
log::info!("Loaded project: {:?}", path);
let mut global = PROJECT.write();
*global = config;
self.scene_command = SceneCommand::SwitchScene("editor".to_string());
}
Err(e) => {
let error_msg = if e.to_string().contains("missing field") {
"Project version is outdated. Please update your .eucp file."
} else {
&e.to_string()
};
self.toast.add(egui_toast::Toast {
kind: egui_toast::ToastKind::Error,
text: error_msg.to_string().into(),
options: ToastOptions::default()
.duration_in_seconds(8.0)
.show_progress(true),
..Default::default()
});
log::error!("Failed to load project: {}", e);
}
}
} else {
log::info!("User cancelled file dialog");
}
self.is_in_file_dialogue = false;
}
let mut show_new_project = self.show_new_project;
egui::Window::new("Create New Project")
.open(&mut show_new_project)
.resizable(true)
.collapsible(false)
.fixed_size(screen_size)
.show(&egui_ctx, |ui| {
ui.vertical(|ui| {
ui.heading("Project Name:");
ui.label("MyGame");
ui.add_space(5.0);
ui.text_edit_singleline(&mut self.project_name);
ui.add_space(5.0);
ui.heading("Project Domain:");
ui.label("com.example");
ui.add_space(5.0);
ui.text_edit_singleline(&mut self.project_domain);
ui.add_space(10.0);
ui.heading("Project Location:");
ui.add_space(5.0);
if let Some(ref path) = self.project_path {
ui.label(format!("Chosen location: {}", path.display()));
ui.add_space(5.0);
}
if ui.button("Choose Location").clicked() {
local_select_project = true;
}
ui.add_space(10.0);
let can_create = self.project_path.is_some() && !self.project_name.is_empty();
if ui
.add_enabled(
can_create && self.project_creation_handle.is_none(),
egui::Button::new("Create Project"),
)
.clicked()
{
log::info!("Creating new project at {:?}", self.project_path);
self.start_project_creation(graphics.future_queue.clone());
}
});
});
self.show_new_project = show_new_project;
if local_select_project {
log::debug!("Opening folder picker");
self.is_in_file_dialogue = true;
let name = self.project_name.clone();
if let Some(path) = FileDialog::new()
.set_title("Select Project Folder")
.set_file_name(&name)
.pick_folder()
{
self.project_path = Some(path.clone());
log::debug!("Selected project location: {:?}", path);
}
self.is_in_file_dialogue = false;
}
if self.show_progress {
egui::Window::new("Creating Project...")
.collapsible(false)
.resizable(false)
.fixed_size([400.0, 150.0])
.show(&egui_ctx, |ui| {
ui.label(&self.progress_message);
ui.add_space(10.0);
ui.add(egui::ProgressBar::new(self.progress).show_percentage());
if let Some(errors) = &self.project_error {
ui.add_space(10.0);
ui.colored_label(egui::Color32::RED, "Errors encountered:");
for err in errors {
ui.label(err);
}
}
});
}
self.toast.show(ui);
}
fn exit(&mut self, _event_loop: &ActiveEventLoop) {
log::info!("Exiting main menu scene");
}
fn run_command(&mut self) -> SceneCommand {
std::mem::replace(&mut self.scene_command, SceneCommand::None)
}
}
impl Keyboard for MainMenu {
fn key_down(&mut self, key: KeyCode, _event_loop: &ActiveEventLoop) {
if key == KeyCode::Escape && !self.show_new_project && !self.is_in_file_dialogue {
self.scene_command = SceneCommand::Quit(None);
}
}
fn key_up(&mut self, _key: KeyCode, _event_loop: &ActiveEventLoop) {}
}
impl Mouse for MainMenu {
fn mouse_move(&mut self, _position: PhysicalPosition<f64>, _delta: Option<(f64, f64)>) {}
fn mouse_down(&mut self, _button: MouseButton) {}
fn mouse_up(&mut self, _button: MouseButton) {}
}
impl Controller for MainMenu {
fn button_down(&mut self, button: gilrs::Button, id: gilrs::GamepadId) {
debug_once!("Controller button {:?} pressed! [{}]", button, id);
}
fn button_up(&mut self, button: gilrs::Button, id: gilrs::GamepadId) {
debug_once!("Controller button {:?} released! [{}]", button, id);
}
fn left_stick_changed(&mut self, x: f32, y: f32, id: gilrs::GamepadId) {
debug_once!("Left stick changed: x = {} | y = {} | id = {}", x, y, id);
}
fn right_stick_changed(&mut self, x: f32, y: f32, id: gilrs::GamepadId) {
debug_once!("Right stick changed: x = {} | y = {} | id = {}", x, y, id);
}
fn on_connect(&mut self, id: gilrs::GamepadId) {
debug_once!("Controller connected [{}]", id);
}
fn on_disconnect(&mut self, id: gilrs::GamepadId) {
debug_once!("Controller disconnected [{}]", id);
}
}