Skip to content

Commit

Permalink
- changed refresh icon stuff for web assembly version
Browse files Browse the repository at this point in the history
  • Loading branch information
RealRTTV committed Mar 24, 2024
1 parent d38df75 commit d5b33e8
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 104 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
14 changes: 7 additions & 7 deletions src/element_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -110,7 +110,7 @@ impl ElementAction {
}

#[allow(clippy::too_many_lines)]
pub fn apply(self, key: Option<CompactString>, indices: Box<[usize]>, tab_uuid: Uuid, true_line_number: usize, line_number: usize, element: &mut NbtElement, bookmarks: &mut Bookmarks, subscription: &mut Option<FileUpdateSubscription>) -> Option<WorkbenchAction> {
pub fn apply(self, key: Option<CompactString>, indices: Box<[usize]>, _tab_uuid: Uuid, true_line_number: usize, line_number: usize, element: &mut NbtElement, bookmarks: &mut Bookmarks, _subscription: &mut Option<FileUpdateSubscription>) -> Option<WorkbenchAction> {
#[must_use]
#[cfg(not(target_arch = "wasm32"))]
fn open_file(str: &str) -> bool {
Expand Down Expand Up @@ -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,
});
}
}
Expand Down Expand Up @@ -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,
});
}
}
Expand Down
67 changes: 20 additions & 47 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
Expand Down
68 changes: 38 additions & 30 deletions src/tab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
};
Expand Down Expand Up @@ -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)?;
Expand All @@ -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(())
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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| {
Expand Down
26 changes: 14 additions & 12 deletions src/workbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit d5b33e8

Please sign in to comment.