mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-16 23:08:05 +08:00
Remove surface and window from ApplicationIo (#3941)
* Remove surface and window from ApplicationIo * Seperate Wasm and Native ApplicationIo * Fix warnings * Fix tests * Remove redundant PlatformApplicationIo::new_offscreen * Fixup * Remove unused From implementaitions for ApplicationIo
This commit is contained in:
55
node-graph/graph-craft/src/application_io.rs
Normal file
55
node-graph/graph-craft/src/application_io.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use dyn_any::StaticType;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
mod native;
|
||||
#[cfg(target_family = "wasm")]
|
||||
mod wasm;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type PlatformApplicationIo = native::NativeApplicationIo;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type PlatformApplicationIo = wasm::WasmApplicationIo;
|
||||
|
||||
pub type PlatformEditorApi = graphene_application_io::EditorApi<PlatformApplicationIo>;
|
||||
|
||||
static WGPU_AVAILABLE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
|
||||
|
||||
/// Returns:
|
||||
/// - `None` if the availability of WGPU has not been determined yet
|
||||
/// - `Some(true)` if WGPU is available
|
||||
/// - `Some(false)` if WGPU is not available
|
||||
pub fn wgpu_available() -> Option<bool> {
|
||||
match WGPU_AVAILABLE.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
-1 => None,
|
||||
0 => Some(false),
|
||||
_ => Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_wgpu_available(available: bool) {
|
||||
WGPU_AVAILABLE.store(available as i8, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EditorPreferences {
|
||||
/// Maximum render region size in pixels along one dimension of the square area.
|
||||
pub max_render_region_size: u32,
|
||||
}
|
||||
|
||||
impl graphene_application_io::GetEditorPreferences for EditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32 {
|
||||
let size = self.max_render_region_size.min(u32::MAX.isqrt());
|
||||
size.pow(2)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EditorPreferences {
|
||||
fn default() -> Self {
|
||||
Self { max_render_region_size: 1280 }
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for EditorPreferences {
|
||||
type Static = EditorPreferences;
|
||||
}
|
||||
113
node-graph/graph-craft/src/application_io/native.rs
Normal file
113
node-graph/graph-craft/src/application_io/native.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use dyn_any::StaticType;
|
||||
use graphene_application_io::{ApplicationError, ApplicationIo, ResourceFuture};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
#[cfg(feature = "tokio")]
|
||||
use tokio::io::AsyncReadExt;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::JsCast;
|
||||
#[cfg(feature = "wgpu")]
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct NativeApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub(crate) gpu_executor: Option<WgpuExecutor>,
|
||||
pub resources: HashMap<String, Arc<[u8]>>,
|
||||
}
|
||||
|
||||
impl NativeApplicationIo {
|
||||
pub async fn new() -> Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
let executor = WgpuExecutor::new().await;
|
||||
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let wgpu_available = false;
|
||||
#[cfg(feature = "wgpu")]
|
||||
let wgpu_available = executor.is_some();
|
||||
super::set_wgpu_available(wgpu_available);
|
||||
|
||||
let mut io = Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor,
|
||||
resources: HashMap::new(),
|
||||
};
|
||||
io.resources.insert("null".to_string(), Arc::from(include_bytes!("../null.png").to_vec()));
|
||||
|
||||
io
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn new_with_context(context: wgpu_executor::WgpuContext) -> Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
let executor = WgpuExecutor::with_context(context);
|
||||
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let wgpu_available = false;
|
||||
#[cfg(feature = "wgpu")]
|
||||
let wgpu_available = executor.is_some();
|
||||
super::set_wgpu_available(wgpu_available);
|
||||
|
||||
let mut io = Self {
|
||||
gpu_executor: executor,
|
||||
resources: HashMap::new(),
|
||||
};
|
||||
|
||||
io.resources.insert("null".to_string(), Arc::from(include_bytes!("../null.png").to_vec()));
|
||||
|
||||
io
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationIo for NativeApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
type Executor = WgpuExecutor;
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
type Executor = ();
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
self.gpu_executor.as_ref()
|
||||
}
|
||||
|
||||
fn load_resource(&self, url: impl AsRef<str>) -> Result<ResourceFuture, ApplicationError> {
|
||||
let url = url::Url::parse(url.as_ref()).map_err(|_| ApplicationError::InvalidUrl)?;
|
||||
log::trace!("Loading resource: {url:?}");
|
||||
match url.scheme() {
|
||||
#[cfg(feature = "tokio")]
|
||||
"file" => {
|
||||
let path = url.to_file_path().map_err(|_| ApplicationError::NotFound)?;
|
||||
let path = path.to_str().ok_or(ApplicationError::NotFound)?;
|
||||
let path = path.to_owned();
|
||||
Ok(Box::pin(async move {
|
||||
let file = tokio::fs::File::open(path).await.map_err(|_| ApplicationError::NotFound)?;
|
||||
let mut reader = tokio::io::BufReader::new(file);
|
||||
let mut data = Vec::new();
|
||||
reader.read_to_end(&mut data).await.map_err(|_| ApplicationError::NotFound)?;
|
||||
Ok(Arc::from(data))
|
||||
}) as ResourceFuture)
|
||||
}
|
||||
"http" | "https" => {
|
||||
let url = url.to_string();
|
||||
Ok(Box::pin(async move {
|
||||
let client = reqwest::Client::new();
|
||||
let response = client.get(url).send().await.map_err(|_| ApplicationError::NotFound)?;
|
||||
let data = response.bytes().await.map_err(|_| ApplicationError::NotFound)?;
|
||||
Ok(Arc::from(data.to_vec()))
|
||||
}) as ResourceFuture)
|
||||
}
|
||||
"graphite" => {
|
||||
let path = url.path();
|
||||
let path = path.to_owned();
|
||||
log::trace!("Loading local resource: {path}");
|
||||
let data = self.resources.get(&path).ok_or(ApplicationError::NotFound)?.clone();
|
||||
Ok(Box::pin(async move { Ok(data.clone()) }) as ResourceFuture)
|
||||
}
|
||||
_ => Err(ApplicationError::NotFound),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for NativeApplicationIo {
|
||||
type Static = NativeApplicationIo;
|
||||
}
|
||||
105
node-graph/graph-craft/src/application_io/wasm.rs
Normal file
105
node-graph/graph-craft/src/application_io/wasm.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use dyn_any::StaticType;
|
||||
use graphene_application_io::{ApplicationError, ApplicationIo, ResourceFuture};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
#[cfg(feature = "tokio")]
|
||||
use tokio::io::AsyncReadExt;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::JsCast;
|
||||
#[cfg(feature = "wgpu")]
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WasmApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub(crate) gpu_executor: Option<WgpuExecutor>,
|
||||
pub resources: HashMap<String, Arc<[u8]>>,
|
||||
}
|
||||
|
||||
impl WasmApplicationIo {
|
||||
pub async fn new() -> Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
let executor = if let Some(gpu) = web_sys::window().map(|w| w.navigator().gpu()) {
|
||||
let request_adapter = || {
|
||||
let request_adapter = js_sys::Reflect::get(&gpu, &wasm_bindgen::JsValue::from_str("requestAdapter")).ok()?;
|
||||
let function = request_adapter.dyn_ref::<js_sys::Function>()?;
|
||||
function.call0(&gpu).ok()
|
||||
};
|
||||
let result = request_adapter();
|
||||
match result {
|
||||
None => None,
|
||||
Some(_) => WgpuExecutor::new().await,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let wgpu_available = false;
|
||||
#[cfg(feature = "wgpu")]
|
||||
let wgpu_available = executor.is_some();
|
||||
super::set_wgpu_available(wgpu_available);
|
||||
|
||||
let mut io = Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor,
|
||||
resources: HashMap::new(),
|
||||
};
|
||||
io.resources.insert("null".to_string(), Arc::from(include_bytes!("../null.png").to_vec()));
|
||||
|
||||
io
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationIo for WasmApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
type Executor = WgpuExecutor;
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
type Executor = ();
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
self.gpu_executor.as_ref()
|
||||
}
|
||||
|
||||
fn load_resource(&self, url: impl AsRef<str>) -> Result<ResourceFuture, ApplicationError> {
|
||||
let url = url::Url::parse(url.as_ref()).map_err(|_| ApplicationError::InvalidUrl)?;
|
||||
log::trace!("Loading resource: {url:?}");
|
||||
match url.scheme() {
|
||||
#[cfg(feature = "tokio")]
|
||||
"file" => {
|
||||
let path = url.to_file_path().map_err(|_| ApplicationError::NotFound)?;
|
||||
let path = path.to_str().ok_or(ApplicationError::NotFound)?;
|
||||
let path = path.to_owned();
|
||||
Ok(Box::pin(async move {
|
||||
let file = tokio::fs::File::open(path).await.map_err(|_| ApplicationError::NotFound)?;
|
||||
let mut reader = tokio::io::BufReader::new(file);
|
||||
let mut data = Vec::new();
|
||||
reader.read_to_end(&mut data).await.map_err(|_| ApplicationError::NotFound)?;
|
||||
Ok(Arc::from(data))
|
||||
}) as ResourceFuture)
|
||||
}
|
||||
"http" | "https" => {
|
||||
let url = url.to_string();
|
||||
Ok(Box::pin(async move {
|
||||
let client = reqwest::Client::new();
|
||||
let response = client.get(url).send().await.map_err(|_| ApplicationError::NotFound)?;
|
||||
let data = response.bytes().await.map_err(|_| ApplicationError::NotFound)?;
|
||||
Ok(Arc::from(data.to_vec()))
|
||||
}) as ResourceFuture)
|
||||
}
|
||||
"graphite" => {
|
||||
let path = url.path();
|
||||
let path = path.to_owned();
|
||||
log::trace!("Loading local resource: {path}");
|
||||
let data = self.resources.get(&path).ok_or(ApplicationError::NotFound)?.clone();
|
||||
Ok(Box::pin(async move { Ok(data.clone()) }) as ResourceFuture)
|
||||
}
|
||||
_ => Err(ApplicationError::NotFound),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for WasmApplicationIo {
|
||||
type Static = WasmApplicationIo;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::DocumentNode;
|
||||
use crate::application_io::PlatformEditorApi;
|
||||
use crate::proto::{Any as DAny, FutureAny};
|
||||
use crate::wasm_application_io::WasmEditorApi;
|
||||
use brush_nodes::brush_cache::BrushCache;
|
||||
use brush_nodes::brush_stroke::BrushStroke;
|
||||
use core_types::table::Table;
|
||||
@@ -10,7 +10,6 @@ use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
use glam::{Affine2, Vec2};
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graphene_application_io::{ImageTexture, SurfaceFrame};
|
||||
use graphic_types::Artboard;
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
@@ -40,9 +39,8 @@ macro_rules! tagged_value {
|
||||
None,
|
||||
$( $(#[$meta] ) *$identifier( $ty ), )*
|
||||
RenderOutput(RenderOutput),
|
||||
SurfaceFrame(SurfaceFrame),
|
||||
#[serde(skip)]
|
||||
EditorApi(Arc<WasmEditorApi>)
|
||||
EditorApi(Arc<PlatformEditorApi>)
|
||||
}
|
||||
|
||||
// We must manually implement hashing because some values are floats and so do not reproducibly hash (see FakeHash below)
|
||||
@@ -54,7 +52,6 @@ macro_rules! tagged_value {
|
||||
Self::None => {}
|
||||
$( Self::$identifier(x) => {x.hash(state)}),*
|
||||
Self::RenderOutput(x) => x.hash(state),
|
||||
Self::SurfaceFrame(x) => x.hash(state),
|
||||
Self::EditorApi(x) => x.hash(state),
|
||||
}
|
||||
}
|
||||
@@ -66,7 +63,6 @@ macro_rules! tagged_value {
|
||||
Self::None => Box::new(()),
|
||||
$( Self::$identifier(x) => Box::new(x), )*
|
||||
Self::RenderOutput(x) => Box::new(x),
|
||||
Self::SurfaceFrame(x) => Box::new(x),
|
||||
Self::EditorApi(x) => Box::new(x),
|
||||
}
|
||||
}
|
||||
@@ -76,7 +72,6 @@ macro_rules! tagged_value {
|
||||
Self::None => Arc::new(()),
|
||||
$( Self::$identifier(x) => Arc::new(x), )*
|
||||
Self::RenderOutput(x) => Arc::new(x),
|
||||
Self::SurfaceFrame(x) => Arc::new(x),
|
||||
Self::EditorApi(x) => Arc::new(x),
|
||||
}
|
||||
}
|
||||
@@ -86,8 +81,7 @@ macro_rules! tagged_value {
|
||||
Self::None => concrete!(()),
|
||||
$( Self::$identifier(_) => concrete!($ty), )*
|
||||
Self::RenderOutput(_) => concrete!(RenderOutput),
|
||||
Self::SurfaceFrame(_) => concrete!(SurfaceFrame),
|
||||
Self::EditorApi(_) => concrete!(&WasmEditorApi)
|
||||
Self::EditorApi(_) => concrete!(&PlatformEditorApi)
|
||||
}
|
||||
}
|
||||
/// Attempts to downcast the dynamic type to a tagged value
|
||||
@@ -99,8 +93,6 @@ macro_rules! tagged_value {
|
||||
x if x == TypeId::of::<()>() => Ok(TaggedValue::None),
|
||||
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*downcast(input).unwrap())), )*
|
||||
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(*downcast(input).unwrap())),
|
||||
x if x == TypeId::of::<SurfaceFrame>() => Ok(TaggedValue::SurfaceFrame(*downcast(input).unwrap())),
|
||||
|
||||
|
||||
_ => Err(format!("Cannot convert {:?} to TaggedValue", DynAny::type_name(input.as_ref()))),
|
||||
}
|
||||
@@ -113,8 +105,7 @@ macro_rules! tagged_value {
|
||||
x if x == TypeId::of::<()>() => Ok(TaggedValue::None),
|
||||
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(<$ty as Clone>::clone(input.downcast_ref().unwrap()))), )*
|
||||
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(RenderOutput::clone(input.downcast_ref().unwrap()))),
|
||||
x if x == TypeId::of::<SurfaceFrame>() => Ok(TaggedValue::SurfaceFrame(SurfaceFrame::clone(input.downcast_ref().unwrap()))),
|
||||
_ => Err(format!("Cannot convert {:?} to TaggedValue",std::any::type_name_of_val(input))),
|
||||
_ => Err(format!("Cannot convert {:?} to TaggedValue", std::any::type_name_of_val(input))),
|
||||
}
|
||||
}
|
||||
/// Returns a TaggedValue from the type, where that value is its type's `Default::default()`
|
||||
@@ -148,8 +139,7 @@ macro_rules! tagged_value {
|
||||
Self::None => "()".to_string(),
|
||||
$( Self::$identifier(x) => format!("{:?}", x), )*
|
||||
Self::RenderOutput(_) => "RenderOutput".to_string(),
|
||||
Self::SurfaceFrame(_) => "SurfaceFrame".to_string(),
|
||||
Self::EditorApi(_) => "WasmEditorApi".to_string(),
|
||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -482,11 +472,10 @@ pub struct RenderOutput {
|
||||
pub metadata: RenderMetadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RenderOutputType {
|
||||
CanvasFrame(SurfaceFrame),
|
||||
#[serde(skip)]
|
||||
Texture(ImageTexture),
|
||||
Texture(graphene_application_io::ImageTexture),
|
||||
#[serde(skip)]
|
||||
Buffer {
|
||||
data: Vec<u8>,
|
||||
@@ -497,8 +486,36 @@ pub enum RenderOutputType {
|
||||
svg: String,
|
||||
image_data: Vec<(u64, Image<Color>)>,
|
||||
},
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame {
|
||||
canvas_id: u64,
|
||||
resolution: DVec2,
|
||||
},
|
||||
}
|
||||
|
||||
impl Hash for RenderOutputType {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
match self {
|
||||
Self::Texture(texture) => {
|
||||
texture.hash(state);
|
||||
}
|
||||
Self::Buffer { data, width, height } => {
|
||||
data.hash(state);
|
||||
width.hash(state);
|
||||
height.hash(state);
|
||||
}
|
||||
Self::Svg { svg, image_data } => {
|
||||
svg.hash(state);
|
||||
image_data.hash(state);
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.hash(state);
|
||||
resolution.to_array().iter().for_each(|x| x.to_bits().hash(state));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Hash for RenderOutput {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.data.hash(state)
|
||||
|
||||
@@ -5,9 +5,9 @@ extern crate core_types;
|
||||
|
||||
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, generic};
|
||||
|
||||
pub mod application_io;
|
||||
pub mod document;
|
||||
pub mod graphene_compiler;
|
||||
pub mod proto;
|
||||
#[cfg(feature = "loading")]
|
||||
pub mod util;
|
||||
pub mod wasm_application_io;
|
||||
|
||||
@@ -1,361 +0,0 @@
|
||||
use dyn_any::StaticType;
|
||||
use graphene_application_io::{ApplicationError, ApplicationIo, ResourceFuture, SurfaceHandle, SurfaceId};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use js_sys::{Object, Reflect};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
#[cfg(feature = "tokio")]
|
||||
use tokio::io::AsyncReadExt;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::JsCast;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::JsValue;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use web_sys::HtmlCanvasElement;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use web_sys::window;
|
||||
#[cfg(feature = "wgpu")]
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WindowWrapper {
|
||||
#[cfg(target_family = "wasm")]
|
||||
window: SurfaceHandle<HtmlCanvasElement>,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
window: SurfaceHandle<Arc<dyn winit::window::Window>>,
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl Drop for WindowWrapper {
|
||||
fn drop(&mut self) {
|
||||
let window = window().expect("should have a window in this context");
|
||||
let window = Object::from(window);
|
||||
|
||||
let image_canvases_key = JsValue::from_str("imageCanvases");
|
||||
|
||||
let wrapper = || {
|
||||
if let Ok(canvases) = Reflect::get(&window, &image_canvases_key) {
|
||||
// Convert key and value to JsValue
|
||||
let js_key = JsValue::from_str(self.window.window_id.to_string().as_str());
|
||||
|
||||
// Use Reflect API to set property
|
||||
Reflect::delete_property(&canvases.into(), &js_key)?;
|
||||
}
|
||||
Ok::<_, JsValue>(())
|
||||
};
|
||||
|
||||
wrapper().expect("should be able to set canvas in global scope")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for WindowWrapper {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for WindowWrapper {}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WasmApplicationIo {
|
||||
#[cfg(target_family = "wasm")]
|
||||
ids: AtomicU64,
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub(crate) gpu_executor: Option<WgpuExecutor>,
|
||||
windows: Vec<WindowWrapper>,
|
||||
pub resources: HashMap<String, Arc<[u8]>>,
|
||||
}
|
||||
|
||||
static WGPU_AVAILABLE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
|
||||
|
||||
/// Returns:
|
||||
/// - `None` if the availability of WGPU has not been determined yet
|
||||
/// - `Some(true)` if WGPU is available
|
||||
/// - `Some(false)` if WGPU is not available
|
||||
pub fn wgpu_available() -> Option<bool> {
|
||||
match WGPU_AVAILABLE.load(Ordering::SeqCst) {
|
||||
-1 => None,
|
||||
0 => Some(false),
|
||||
_ => Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
impl WasmApplicationIo {
|
||||
pub async fn new() -> Self {
|
||||
#[cfg(all(feature = "wgpu", target_family = "wasm"))]
|
||||
let executor = if let Some(gpu) = web_sys::window().map(|w| w.navigator().gpu()) {
|
||||
let request_adapter = || {
|
||||
let request_adapter = js_sys::Reflect::get(&gpu, &wasm_bindgen::JsValue::from_str("requestAdapter")).ok()?;
|
||||
let function = request_adapter.dyn_ref::<js_sys::Function>()?;
|
||||
Some(function.call0(&gpu).ok())
|
||||
};
|
||||
let result = request_adapter();
|
||||
match result {
|
||||
None => None,
|
||||
Some(_) => WgpuExecutor::new().await,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
#[cfg(all(feature = "wgpu", not(target_family = "wasm")))]
|
||||
let executor = WgpuExecutor::new().await;
|
||||
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let wgpu_available = false;
|
||||
#[cfg(feature = "wgpu")]
|
||||
let wgpu_available = executor.is_some();
|
||||
WGPU_AVAILABLE.store(wgpu_available as i8, Ordering::SeqCst);
|
||||
|
||||
let mut io = Self {
|
||||
#[cfg(target_family = "wasm")]
|
||||
ids: AtomicU64::new(0),
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor,
|
||||
windows: Vec::new(),
|
||||
resources: HashMap::new(),
|
||||
};
|
||||
let window = io.create_window();
|
||||
io.windows.push(WindowWrapper { window });
|
||||
io.resources.insert("null".to_string(), Arc::from(include_bytes!("null.png").to_vec()));
|
||||
|
||||
io
|
||||
}
|
||||
|
||||
pub async fn new_offscreen() -> Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
let executor = WgpuExecutor::new().await;
|
||||
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let wgpu_available = false;
|
||||
#[cfg(feature = "wgpu")]
|
||||
let wgpu_available = executor.is_some();
|
||||
WGPU_AVAILABLE.store(wgpu_available as i8, Ordering::SeqCst);
|
||||
|
||||
let mut io = Self {
|
||||
#[cfg(target_family = "wasm")]
|
||||
ids: AtomicU64::new(0),
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor,
|
||||
windows: Vec::new(),
|
||||
resources: HashMap::new(),
|
||||
};
|
||||
|
||||
io.resources.insert("null".to_string(), Arc::from(include_bytes!("null.png").to_vec()));
|
||||
|
||||
io
|
||||
}
|
||||
#[cfg(all(not(target_family = "wasm"), feature = "wgpu"))]
|
||||
pub fn new_with_context(context: wgpu_executor::WgpuContext) -> Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
let executor = WgpuExecutor::with_context(context);
|
||||
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let wgpu_available = false;
|
||||
#[cfg(feature = "wgpu")]
|
||||
let wgpu_available = executor.is_some();
|
||||
WGPU_AVAILABLE.store(wgpu_available as i8, Ordering::SeqCst);
|
||||
|
||||
let mut io = Self {
|
||||
gpu_executor: executor,
|
||||
windows: Vec::new(),
|
||||
resources: HashMap::new(),
|
||||
};
|
||||
|
||||
io.resources.insert("null".to_string(), Arc::from(include_bytes!("null.png").to_vec()));
|
||||
|
||||
io
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for WasmApplicationIo {
|
||||
type Static = WasmApplicationIo;
|
||||
}
|
||||
|
||||
impl<'a> From<&'a WasmEditorApi> for &'a WasmApplicationIo {
|
||||
fn from(editor_api: &'a WasmEditorApi) -> Self {
|
||||
editor_api.application_io.as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "wgpu")]
|
||||
impl<'a> From<&'a WasmApplicationIo> for &'a WgpuExecutor {
|
||||
fn from(app_io: &'a WasmApplicationIo) -> Self {
|
||||
app_io.gpu_executor.as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub type WasmEditorApi = graphene_application_io::EditorApi<WasmApplicationIo>;
|
||||
|
||||
impl ApplicationIo for WasmApplicationIo {
|
||||
#[cfg(target_family = "wasm")]
|
||||
type Surface = HtmlCanvasElement;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type Surface = Arc<dyn winit::window::Window>;
|
||||
#[cfg(feature = "wgpu")]
|
||||
type Executor = WgpuExecutor;
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
type Executor = ();
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn create_window(&self) -> SurfaceHandle<Self::Surface> {
|
||||
let wrapper = || {
|
||||
let document = window().expect("should have a window in this context").document().expect("window should have a document");
|
||||
|
||||
let canvas: HtmlCanvasElement = document.create_element("canvas")?.dyn_into::<HtmlCanvasElement>()?;
|
||||
let id = self.ids.fetch_add(1, Ordering::SeqCst);
|
||||
// store the canvas in the global scope so it doesn't get garbage collected
|
||||
let window = window().expect("should have a window in this context");
|
||||
let window = Object::from(window);
|
||||
|
||||
let image_canvases_key = JsValue::from_str("imageCanvases");
|
||||
|
||||
let mut canvases = Reflect::get(&window, &image_canvases_key);
|
||||
if canvases.is_err() {
|
||||
Reflect::set(&JsValue::from(web_sys::window().unwrap()), &image_canvases_key, &Object::new()).unwrap();
|
||||
canvases = Reflect::get(&window, &image_canvases_key);
|
||||
}
|
||||
|
||||
// Convert key and value to JsValue
|
||||
let js_key = JsValue::from_str(id.to_string().as_str());
|
||||
let js_value = JsValue::from(canvas.clone());
|
||||
|
||||
let canvases = Object::from(canvases.unwrap());
|
||||
|
||||
// Use Reflect API to set property
|
||||
Reflect::set(&canvases, &js_key, &js_value)?;
|
||||
Ok::<_, JsValue>(SurfaceHandle {
|
||||
window_id: SurfaceId(id),
|
||||
surface: canvas,
|
||||
})
|
||||
};
|
||||
|
||||
wrapper().expect("should be able to set canvas in global scope")
|
||||
}
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn create_window(&self) -> SurfaceHandle<Self::Surface> {
|
||||
todo!("winit api changed, calling create_window on EventLoop is deprecated");
|
||||
|
||||
// log::trace!("Spawning window");
|
||||
|
||||
// #[cfg(all(not(test), target_os = "linux", feature = "wayland"))]
|
||||
// use winit::platform::wayland::EventLoopBuilderExtWayland;
|
||||
|
||||
// #[cfg(all(not(test), target_os = "linux", feature = "wayland"))]
|
||||
// let event_loop = winit::event_loop::EventLoopBuilder::new().with_any_thread(true).build().unwrap();
|
||||
// #[cfg(not(all(not(test), target_os = "linux", feature = "wayland")))]
|
||||
// let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||
|
||||
// let window = event_loop
|
||||
// .create_window(
|
||||
// winit::window::WindowAttributes::default()
|
||||
// .with_title("Graphite")
|
||||
// .with_inner_size(winit::dpi::PhysicalSize::new(800, 600)),
|
||||
// )
|
||||
// .unwrap();
|
||||
|
||||
// SurfaceHandle {
|
||||
// window_id: SurfaceId(window.id().into()),
|
||||
// surface: Arc::new(window),
|
||||
// }
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn destroy_window(&self, surface_id: SurfaceId) {
|
||||
let window = window().expect("should have a window in this context");
|
||||
let window = Object::from(window);
|
||||
|
||||
let image_canvases_key = JsValue::from_str("imageCanvases");
|
||||
|
||||
let wrapper = || {
|
||||
if let Ok(canvases) = Reflect::get(&window, &image_canvases_key) {
|
||||
// Convert key and value to JsValue
|
||||
let js_key = JsValue::from_str(surface_id.0.to_string().as_str());
|
||||
|
||||
// Use Reflect API to set property
|
||||
Reflect::delete_property(&canvases.into(), &js_key)?;
|
||||
}
|
||||
Ok::<_, JsValue>(())
|
||||
};
|
||||
|
||||
wrapper().expect("should be able to set canvas in global scope")
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn destroy_window(&self, _surface_id: SurfaceId) {}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
self.gpu_executor.as_ref()
|
||||
}
|
||||
|
||||
fn load_resource(&self, url: impl AsRef<str>) -> Result<ResourceFuture, ApplicationError> {
|
||||
let url = url::Url::parse(url.as_ref()).map_err(|_| ApplicationError::InvalidUrl)?;
|
||||
log::trace!("Loading resource: {url:?}");
|
||||
match url.scheme() {
|
||||
#[cfg(feature = "tokio")]
|
||||
"file" => {
|
||||
let path = url.to_file_path().map_err(|_| ApplicationError::NotFound)?;
|
||||
let path = path.to_str().ok_or(ApplicationError::NotFound)?;
|
||||
let path = path.to_owned();
|
||||
Ok(Box::pin(async move {
|
||||
let file = tokio::fs::File::open(path).await.map_err(|_| ApplicationError::NotFound)?;
|
||||
let mut reader = tokio::io::BufReader::new(file);
|
||||
let mut data = Vec::new();
|
||||
reader.read_to_end(&mut data).await.map_err(|_| ApplicationError::NotFound)?;
|
||||
Ok(Arc::from(data))
|
||||
}) as ResourceFuture)
|
||||
}
|
||||
"http" | "https" => {
|
||||
let url = url.to_string();
|
||||
Ok(Box::pin(async move {
|
||||
let client = reqwest::Client::new();
|
||||
let response = client.get(url).send().await.map_err(|_| ApplicationError::NotFound)?;
|
||||
let data = response.bytes().await.map_err(|_| ApplicationError::NotFound)?;
|
||||
Ok(Arc::from(data.to_vec()))
|
||||
}) as ResourceFuture)
|
||||
}
|
||||
"graphite" => {
|
||||
let path = url.path();
|
||||
let path = path.to_owned();
|
||||
log::trace!("Loading local resource: {path}");
|
||||
let data = self.resources.get(&path).ok_or(ApplicationError::NotFound)?.clone();
|
||||
Ok(Box::pin(async move { Ok(data.clone()) }) as ResourceFuture)
|
||||
}
|
||||
_ => Err(ApplicationError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn window(&self) -> Option<SurfaceHandle<Self::Surface>> {
|
||||
self.windows.first().map(|wrapper| wrapper.window.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub type WasmSurfaceHandle = SurfaceHandle<wgpu_executor::Window>;
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub type WasmSurfaceHandleFrame = graphene_application_io::SurfaceHandleFrame<wgpu_executor::Window>;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EditorPreferences {
|
||||
/// Maximum render region size in pixels along one dimension of the square area.
|
||||
pub max_render_region_size: u32,
|
||||
}
|
||||
|
||||
impl graphene_application_io::GetEditorPreferences for EditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32 {
|
||||
let size = self.max_render_region_size.min(u32::MAX.isqrt());
|
||||
size.pow(2)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EditorPreferences {
|
||||
fn default() -> Self {
|
||||
Self { max_render_region_size: 1280 }
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for EditorPreferences {
|
||||
type Static = EditorPreferences;
|
||||
}
|
||||
Reference in New Issue
Block a user