From d5b33e8e7cc925ef70c99d950c97133b480791a4 Mon Sep 17 00:00:00 2001 From: RTTV Date: Sun, 24 Mar 2024 13:23:03 -0400 Subject: [PATCH] - changed refresh icon stuff for web assembly version --- Cargo.toml | 6 ++-- src/element_action.rs | 14 ++++----- src/main.rs | 67 +++++++++++++----------------------------- src/tab.rs | 68 ++++++++++++++++++++++++------------------- src/window.rs | 13 +++++---- src/workbench.rs | 26 +++++++++-------- 6 files changed, 90 insertions(+), 104 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5bdab2e..2c76282 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,9 +9,9 @@ keywords = ["nbt", "window", "unsafe", "editor", "tree"] categories = ["graphics", "rendering", "text-editors", "parser-implementations"] # Required for Wasm target, but breaks `winres` -#[lib] -#crate-type = ["cdylib", "rlib"] -#path = "src/main.rs" +[lib] +crate-type = ["cdylib", "rlib"] +path = "src/main.rs" [package.metadata.winres] diff --git a/src/element_action.rs b/src/element_action.rs index 302be89..03fa7fb 100644 --- a/src/element_action.rs +++ b/src/element_action.rs @@ -7,9 +7,9 @@ use compact_str::CompactString; use notify::{EventKind, PollWatcher, RecursiveMode, Watcher}; use uuid::Uuid; -use crate::{panic_unchecked, set_clipboard, FileUpdateSubscription, since_epoch}; +use crate::{panic_unchecked, set_clipboard, FileUpdateSubscription}; #[cfg(not(target_arch = "wasm32"))] -use crate::{FileUpdateSubscriptionType, assets::{OPEN_ARRAY_IN_HEX_UV, OPEN_IN_TXT}}; +use crate::{FileUpdateSubscriptionType, assets::{OPEN_ARRAY_IN_HEX_UV, OPEN_IN_TXT}, since_epoch}; use crate::assets::{ACTION_WHEEL_Z, COPY_FORMATTED_UV, COPY_RAW_UV, SORT_COMPOUND_BY_NAME, SORT_COMPOUND_BY_TYPE}; use crate::elements::chunk::NbtChunk; use crate::elements::compound::NbtCompound; @@ -110,7 +110,7 @@ impl ElementAction { } #[allow(clippy::too_many_lines)] - pub fn apply(self, key: Option, indices: Box<[usize]>, tab_uuid: Uuid, true_line_number: usize, line_number: usize, element: &mut NbtElement, bookmarks: &mut Bookmarks, subscription: &mut Option) -> Option { + pub fn apply(self, key: Option, indices: Box<[usize]>, _tab_uuid: Uuid, true_line_number: usize, line_number: usize, element: &mut NbtElement, bookmarks: &mut Bookmarks, _subscription: &mut Option) -> Option { #[must_use] #[cfg(not(target_arch = "wasm32"))] fn open_file(str: &str) -> bool { @@ -207,12 +207,12 @@ impl ElementAction { drop(file); if watcher.watch(&path, RecursiveMode::NonRecursive).is_err() { break 'm; }; if !open_file(&path.display().to_string()) { break 'm; } - *subscription = Some(FileUpdateSubscription { + *_subscription = Some(FileUpdateSubscription { subscription_type, indices, rx, watcher, - tab_uuid, + tab_uuid: _tab_uuid, }); } } @@ -257,12 +257,12 @@ impl ElementAction { drop(file); if watcher.watch(&path, RecursiveMode::NonRecursive).is_err() { break 'm; }; if !open_file(&path.display().to_string()) { break 'm; } - *subscription = Some(FileUpdateSubscription { + *_subscription = Some(FileUpdateSubscription { subscription_type: FileUpdateSubscriptionType::Snbt, indices, rx, watcher, - tab_uuid, + tab_uuid: _tab_uuid, }); } } diff --git a/src/main.rs b/src/main.rs index f3c97c0..979edab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,53 +1,27 @@ -#![warn( - clippy::pedantic, - clippy::nursery, - clippy::perf, - clippy::correctness, - clippy::cargo, - clippy::style, - clippy::complexity, - clippy::unused_unit, - clippy::unused_async, - clippy::unused_peekable, - clippy::unused_self, - clippy::unused_format_specs, - clippy::unused_io_amount, - clippy::unused_rounding, - clippy::extra_unused_lifetimes, - clippy::extra_unused_type_parameters, - clippy::unwrap_used -)] #![allow( semicolon_in_expressions_from_macros, internal_features, - clippy::unreadable_literal, - clippy::cast_precision_loss, - clippy::cast_lossless, - clippy::cast_sign_loss, - clippy::cast_possible_truncation, - clippy::collapsible_if, - clippy::collapsible_else_if, - clippy::redundant_else, - clippy::cast_possible_wrap, - clippy::multiple_crate_versions + incomplete_features, +)] +#![feature( + adt_const_params, + array_chunks, + box_patterns, + const_black_box, + const_collections_with_hasher, + const_mut_refs, + core_intrinsics, + iter_array_chunks, + iter_next_chunk, + lazy_cell, + let_chains, + maybe_uninit_array_assume_init, + maybe_uninit_uninit_array, + new_uninit, + optimize_attribute, + stmt_expr_attributes, + unchecked_math )] -#![feature(adt_const_params)] -#![feature(array_chunks)] -#![feature(box_patterns)] -#![feature(const_black_box)] -#![feature(const_collections_with_hasher)] -#![feature(const_mut_refs)] -#![feature(core_intrinsics)] -#![feature(iter_array_chunks)] -#![feature(iter_next_chunk)] -#![feature(lazy_cell)] -#![feature(let_chains)] -#![feature(maybe_uninit_array_assume_init)] -#![feature(maybe_uninit_uninit_array)] -#![feature(new_uninit)] -#![feature(optimize_attribute)] -#![feature(stmt_expr_attributes)] -#![feature(unchecked_math)] #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] use std::cell::UnsafeCell; @@ -274,7 +248,6 @@ pub fn main() -> ! { /// * wiki page for docs on minecraft's format of stuff /// * [chunk](NbtChunk) section rendering /// # Minor Features -/// * open icon for exe ver /// * gear icon to swap toolbar with settings panel /// * __ctrl + h__, open a playground `nbt` file to help with user interaction (bonus points if I have some way to tell if you haven't used this editor before) /// * [`last_modified`](NbtChunk) field actually gets some impl diff --git a/src/tab.rs b/src/tab.rs index e632124..f5c40fb 100644 --- a/src/tab.rs +++ b/src/tab.rs @@ -69,35 +69,36 @@ impl Tab { }) } + #[cfg(any(target_os = "windows", target_os = "apple", target_os = "linux"))] pub fn save(&mut self, force_dialog: bool) -> Result<()> { - #[cfg(any(target_os = "windows", target_os = "apple", target_os = "linux"))] { - let path = self.path.as_deref().unwrap_or(self.name.as_ref().as_ref()); - if !path.exists() || force_dialog { - let mut builder = native_dialog::FileDialog::new(); - if self.value.id() == NbtRegion::ID { - builder = builder.add_filter("Region File", &["mca", "mcr"]); - } else { - builder = builder.add_filter("NBT File", &["nbt", "snbt", "dat", "dat_old", "dat_mcr", "old"]); - } - let path = builder.show_save_single_file()?.ok_or_else(|| anyhow!("Save cancelled"))?; - self.name = path.file_name().and_then(|x| x.to_str()).expect("Path has a filename").to_string().into_boxed_str(); - std::fs::write(&path, self.compression.encode(&self.value))?; - self.path = Some(path); - self.history_changed = false; - Ok(()) + let path = self.path.as_deref().unwrap_or(self.name.as_ref().as_ref()); + if !path.exists() || force_dialog { + let mut builder = native_dialog::FileDialog::new(); + if self.value.id() == NbtRegion::ID { + builder = builder.add_filter("Region File", &["mca", "mcr"]); } else { - std::fs::write(path, self.compression.encode(&self.value))?; - self.history_changed = false; - Ok(()) + builder = builder.add_filter("NBT File", &["nbt", "snbt", "dat", "dat_old", "dat_mcr", "old"]); } - } - #[cfg(target_arch = "wasm32")] { - let bytes = self.compression.encode(&self.value); - crate::save(self.name.as_ref(), bytes); + let path = builder.show_save_single_file()?.ok_or_else(|| anyhow!("Save cancelled"))?; + self.name = path.file_name().and_then(|x| x.to_str()).expect("Path has a filename").to_string().into_boxed_str(); + std::fs::write(&path, self.compression.encode(&self.value))?; + self.path = Some(path); + self.history_changed = false; + Ok(()) + } else { + std::fs::write(path, self.compression.encode(&self.value))?; + self.history_changed = false; Ok(()) } } + #[cfg(target_arch = "wasm32")] + pub fn save(&mut self, _: bool) -> Result<()> { + let bytes = self.compression.encode(&self.value); + crate::save(self.name.as_ref(), bytes); + Ok(()) + } + #[allow(clippy::too_many_lines)] pub fn render(&self, builder: &mut VertexBufferBuilder, ctx: &mut RenderContext, held: bool, held_entry: Option<&NbtElement>, skip_tooltips: bool, steal_delta: f32) { let mouse_x = ctx.mouse_x; @@ -230,10 +231,17 @@ impl Tab { } { - let enabled = self.path.is_some(); - let widget_uv = if enabled && (296..312).contains(&ctx.mouse_x) && (26..42).contains(&ctx.mouse_y) { - builder.draw_tooltip(&["Refresh Tab (Ctrl + R)"], (ctx.mouse_x, ctx.mouse_y), false); - HOVERED_WIDGET_UV + let enabled = self.path.is_some() && cfg!(not(target_os = "wasm32")); + let widget_uv = if (296..312).contains(&ctx.mouse_x) && (26..42).contains(&ctx.mouse_y) { + #[cfg(target_arch = "wasm32")] + builder.draw_tooltip(&["Refresh Tab (Disabled on WebAssembly version)"], (ctx.mouse_x, ctx.mouse_y), false); + if enabled { + #[cfg(not(target_arch = "wasm32"))] + builder.draw_tooltip(&["Refresh Tab (Ctrl + R)"], (ctx.mouse_x, ctx.mouse_y), false); + HOVERED_WIDGET_UV + } else { + UNSELECTED_WIDGET_UV + } } else { UNSELECTED_WIDGET_UV }; @@ -608,7 +616,7 @@ impl Tab { }) } - #[cfg(not(target_os = "wasm32"))] + #[cfg(not(target_arch = "wasm32"))] pub fn refresh(&mut self, sort_algorithm: SortAlgorithm) -> Result<()> { let Some(path) = self.path.as_deref() else { return Err(anyhow!("File path was not present in tab")) }; let bytes = std::fs::read(path)?; @@ -628,9 +636,9 @@ impl Tab { Ok(()) } - #[cfg(target_os = "wasm32")] - pub fn refresh(&mut self) -> Result<()> { - Err(anyhow!("File refresh not supported on web")) + #[cfg(target_arch = "wasm32")] + pub fn refresh(&mut self, _: SortAlgorithm) -> Result<()> { + Ok(()) } } diff --git a/src/window.rs b/src/window.rs index 26286a3..803436d 100644 --- a/src/window.rs +++ b/src/window.rs @@ -33,7 +33,7 @@ pub const MIN_WINDOW_WIDTH: usize = 720; pub async fn run() -> ! { let event_loop = EventLoop::new().expect("Event loop was unconstructable"); - let mut builder = WindowBuilder::new() + let builder = WindowBuilder::new() .with_title("NBT Workbench") .with_inner_size(PhysicalSize::new(WINDOW_WIDTH as u32, WINDOW_HEIGHT as u32)) .with_min_inner_size(PhysicalSize::new( @@ -48,10 +48,13 @@ pub async fn run() -> ! { ) .expect("valid format"), )); - #[cfg(target_os = "windows")] { - builder = builder.with_drag_and_drop(true) - } - let window = Rc::new(builder.build(&event_loop).expect("Window was constructable")); + let window = Rc::new('a: { + #[cfg(target_os = "windows")] { + break 'a builder.with_drag_and_drop(true) + } + #[cfg(not(target_os = "windows"))] + break 'a builder + }.build(&event_loop).expect("Window was constructable")); #[cfg(target_arch = "wasm32")] let window_size = { web_sys::window().and_then(|window| { diff --git a/src/workbench.rs b/src/workbench.rs index ae6c7a3..5cd82e3 100644 --- a/src/workbench.rs +++ b/src/workbench.rs @@ -1157,24 +1157,26 @@ impl Workbench { } #[inline] + #[cfg(any(target_os = "windows", target_os = "apple", target_os = "linux"))] fn open_file(&mut self, window_properties: &mut WindowProperties) { - #[cfg(any(target_os = "windows", target_os = "apple", target_os = "linux"))] { - match native_dialog::FileDialog::new().set_location("~/Downloads").add_filter("NBT File", &["nbt", "snbt", "dat", "dat_old", "dat_mcr", "old"]).add_filter("Region File", &["mca", "mcr"]).show_open_single_file() { + match native_dialog::FileDialog::new().set_location("~/Downloads").add_filter("NBT File", &["nbt", "snbt", "dat", "dat_old", "dat_mcr", "old"]).add_filter("Region File", &["mca", "mcr"]).show_open_single_file() { + Err(e) => self.alert(Alert::new("Error!", TextColor::Red, e.to_string())), + Ok(None) => {}, + Ok(Some(path)) => match std::fs::read(&path) { + Ok(bytes) => if let Err(e) = self.on_open_file(&path, bytes, window_properties) { + self.alert(Alert::new("Error!", TextColor::Red, e.to_string())) + }, Err(e) => self.alert(Alert::new("Error!", TextColor::Red, e.to_string())), - Ok(None) => {}, - Ok(Some(path)) => match std::fs::read(&path) { - Ok(bytes) => if let Err(e) = self.on_open_file(&path, bytes, window_properties) { - self.alert(Alert::new("Error!", TextColor::Red, e.to_string())) - }, - Err(e) => self.alert(Alert::new("Error!", TextColor::Red, e.to_string())), - } } - }; - #[cfg(target_arch = "wasm32")] { - crate::try_open_dialog(); } } + #[inline] + #[cfg(target_arch = "wasm32")] + fn open_file(&mut self, _: &mut WindowProperties) { + crate::try_open_dialog(); + } + #[inline] #[must_use] fn left_margin(&self) -> usize {