mirror of
https://github.com/slint-ui/slint.git
synced 2025-08-03 18:29:09 +00:00
Improve source structure in the node api (#6164)
* Update api/node/typescript/models.ts Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev> * Code review feedback --------- Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev>
This commit is contained in:
parent
a2ded25914
commit
25ae55b5dd
30 changed files with 528 additions and 450 deletions
123
api/node/rust/interpreter/component_compiler.rs
Normal file
123
api/node/rust/interpreter/component_compiler.rs
Normal file
|
@ -0,0 +1,123 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use super::JsComponentDefinition;
|
||||
use super::JsDiagnostic;
|
||||
use itertools::Itertools;
|
||||
use slint_interpreter::Compiler;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// ComponentCompiler is the entry point to the Slint interpreter that can be used
|
||||
/// to load .slint files or compile them on-the-fly from a string.
|
||||
#[napi(js_name = "ComponentCompiler")]
|
||||
pub struct JsComponentCompiler {
|
||||
internal: Compiler,
|
||||
diagnostics: Vec<slint_interpreter::Diagnostic>,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl JsComponentCompiler {
|
||||
/// Returns a new ComponentCompiler.
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> Self {
|
||||
let mut compiler = Compiler::default();
|
||||
let include_paths = match std::env::var_os("SLINT_INCLUDE_PATH") {
|
||||
Some(paths) => {
|
||||
std::env::split_paths(&paths).filter(|path| !path.as_os_str().is_empty()).collect()
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
let library_paths = match std::env::var_os("SLINT_LIBRARY_PATH") {
|
||||
Some(paths) => std::env::split_paths(&paths)
|
||||
.filter_map(|entry| {
|
||||
entry
|
||||
.to_str()
|
||||
.unwrap_or_default()
|
||||
.split('=')
|
||||
.collect_tuple()
|
||||
.map(|(k, v)| (k.into(), v.into()))
|
||||
})
|
||||
.collect(),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
|
||||
compiler.set_include_paths(include_paths);
|
||||
compiler.set_library_paths(library_paths);
|
||||
Self { internal: compiler, diagnostics: vec![] }
|
||||
}
|
||||
|
||||
#[napi(setter)]
|
||||
pub fn set_include_paths(&mut self, include_paths: Vec<String>) {
|
||||
self.internal.set_include_paths(include_paths.iter().map(|p| PathBuf::from(p)).collect());
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn include_paths(&self) -> Vec<String> {
|
||||
self.internal
|
||||
.include_paths()
|
||||
.iter()
|
||||
.map(|p| p.to_str().unwrap_or_default().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[napi(setter)]
|
||||
pub fn set_library_paths(&mut self, paths: HashMap<String, String>) {
|
||||
let mut library_paths = HashMap::new();
|
||||
for (key, path) in paths {
|
||||
library_paths.insert(key, PathBuf::from(path));
|
||||
}
|
||||
|
||||
self.internal.set_library_paths(library_paths);
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn library_paths(&self) -> HashMap<String, String> {
|
||||
let mut library_paths = HashMap::new();
|
||||
|
||||
for (key, path) in self.internal.library_paths() {
|
||||
library_paths.insert(key.clone(), path.to_str().unwrap_or_default().to_string());
|
||||
}
|
||||
|
||||
library_paths
|
||||
}
|
||||
|
||||
#[napi(setter)]
|
||||
pub fn set_style(&mut self, style: String) {
|
||||
self.internal.set_style(style);
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn style(&self) -> Option<String> {
|
||||
self.internal.style().cloned()
|
||||
}
|
||||
|
||||
// todo: set_file_loader
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn diagnostics(&self) -> Vec<JsDiagnostic> {
|
||||
self.diagnostics.iter().map(|d| JsDiagnostic::from(d.clone())).collect()
|
||||
}
|
||||
|
||||
/// Compile a .slint file into a ComponentDefinition
|
||||
///
|
||||
/// Returns the compiled `ComponentDefinition` if there were no errors.
|
||||
#[napi]
|
||||
pub fn build_from_path(&mut self, path: String) -> HashMap<String, JsComponentDefinition> {
|
||||
let r = spin_on::spin_on(self.internal.build_from_path(PathBuf::from(path)));
|
||||
self.diagnostics = r.diagnostics().collect();
|
||||
r.components().map(|c| (c.name().to_owned(), c.into())).collect()
|
||||
}
|
||||
|
||||
/// Compile some .slint code into a ComponentDefinition
|
||||
#[napi]
|
||||
pub fn build_from_source(
|
||||
&mut self,
|
||||
source_code: String,
|
||||
path: String,
|
||||
) -> HashMap<String, JsComponentDefinition> {
|
||||
let r = spin_on::spin_on(self.internal.build_from_source(source_code, PathBuf::from(path)));
|
||||
self.diagnostics = r.diagnostics().collect();
|
||||
r.components().map(|c| (c.name().to_owned(), c.into())).collect()
|
||||
}
|
||||
}
|
79
api/node/rust/interpreter/component_definition.rs
Normal file
79
api/node/rust/interpreter/component_definition.rs
Normal file
|
@ -0,0 +1,79 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use napi::Result;
|
||||
use slint_interpreter::ComponentDefinition;
|
||||
|
||||
use super::{JsComponentInstance, JsProperty};
|
||||
|
||||
#[napi(js_name = "ComponentDefinition")]
|
||||
pub struct JsComponentDefinition {
|
||||
internal: ComponentDefinition,
|
||||
}
|
||||
|
||||
impl From<ComponentDefinition> for JsComponentDefinition {
|
||||
fn from(definition: ComponentDefinition) -> Self {
|
||||
Self { internal: definition }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl JsComponentDefinition {
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> napi::Result<Self> {
|
||||
Err(napi::Error::from_reason(
|
||||
"ComponentDefinition can only be created by using ComponentCompiler.".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn properties(&self) -> Vec<JsProperty> {
|
||||
self.internal
|
||||
.properties()
|
||||
.map(|(name, value_type)| JsProperty { name, value_type: value_type.into() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn callbacks(&self) -> Vec<String> {
|
||||
self.internal.callbacks().collect()
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn functions(&self) -> Vec<String> {
|
||||
self.internal.functions().collect()
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn globals(&self) -> Vec<String> {
|
||||
self.internal.globals().collect()
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn global_properties(&self, global_name: String) -> Option<Vec<JsProperty>> {
|
||||
self.internal.global_properties(global_name.as_str()).map(|iter| {
|
||||
iter.map(|(name, value_type)| JsProperty { name, value_type: value_type.into() })
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn global_callbacks(&self, global_name: String) -> Option<Vec<String>> {
|
||||
self.internal.global_callbacks(global_name.as_str()).map(|iter| iter.collect())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn global_functions(&self, global_name: String) -> Option<Vec<String>> {
|
||||
self.internal.global_functions(global_name.as_str()).map(|iter| iter.collect())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn create(&self) -> Result<JsComponentInstance> {
|
||||
Ok(self.internal.create().map_err(|e| napi::Error::from_reason(e.to_string()))?.into())
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn name(&self) -> String {
|
||||
self.internal.name().into()
|
||||
}
|
||||
}
|
377
api/node/rust/interpreter/component_instance.rs
Normal file
377
api/node/rust/interpreter/component_instance.rs
Normal file
|
@ -0,0 +1,377 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use i_slint_compiler::langtype::Type;
|
||||
use i_slint_core::window::WindowInner;
|
||||
use napi::{Env, Error, JsFunction, JsUnknown, NapiRaw, NapiValue, Ref, Result};
|
||||
use slint_interpreter::{ComponentHandle, ComponentInstance, Value};
|
||||
|
||||
use crate::JsWindow;
|
||||
|
||||
use super::JsComponentDefinition;
|
||||
|
||||
#[napi(js_name = "ComponentInstance")]
|
||||
pub struct JsComponentInstance {
|
||||
inner: ComponentInstance,
|
||||
}
|
||||
|
||||
impl From<ComponentInstance> for JsComponentInstance {
|
||||
fn from(instance: ComponentInstance) -> Self {
|
||||
Self { inner: instance }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl JsComponentInstance {
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> napi::Result<Self> {
|
||||
Err(napi::Error::from_reason(
|
||||
"ComponentInstance can only be created by using ComponentCompiler.".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn definition(&self) -> JsComponentDefinition {
|
||||
self.inner.definition().into()
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_property(&self, env: Env, name: String) -> Result<JsUnknown> {
|
||||
let value = self
|
||||
.inner
|
||||
.get_property(name.as_ref())
|
||||
.map_err(|e| Error::from_reason(e.to_string()))?;
|
||||
super::value::to_js_unknown(&env, &value)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn set_property(&self, env: Env, prop_name: String, js_value: JsUnknown) -> Result<()> {
|
||||
let ty = self
|
||||
.inner
|
||||
.definition()
|
||||
.properties_and_callbacks()
|
||||
.find_map(|(name, proptype)| if name == prop_name { Some(proptype) } else { None })
|
||||
.ok_or(())
|
||||
.map_err(|_| {
|
||||
napi::Error::from_reason(format!("Property {prop_name} not found in the component"))
|
||||
})?;
|
||||
|
||||
self.inner
|
||||
.set_property(&prop_name, super::value::to_value(&env, js_value, &ty)?)
|
||||
.map_err(|e| Error::from_reason(format!("{e}")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_global_property(
|
||||
&self,
|
||||
env: Env,
|
||||
global_name: String,
|
||||
name: String,
|
||||
) -> Result<JsUnknown> {
|
||||
if !self.definition().globals().contains(&global_name) {
|
||||
return Err(napi::Error::from_reason(format!("Global {global_name} not found")));
|
||||
}
|
||||
let value = self
|
||||
.inner
|
||||
.get_global_property(global_name.as_ref(), name.as_ref())
|
||||
.map_err(|e| Error::from_reason(e.to_string()))?;
|
||||
super::value::to_js_unknown(&env, &value)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn set_global_property(
|
||||
&self,
|
||||
env: Env,
|
||||
global_name: String,
|
||||
prop_name: String,
|
||||
js_value: JsUnknown,
|
||||
) -> Result<()> {
|
||||
let ty = self
|
||||
.inner
|
||||
.definition()
|
||||
.global_properties_and_callbacks(global_name.as_str())
|
||||
.ok_or(napi::Error::from_reason(format!("Global {global_name} not found")))?
|
||||
.find_map(|(name, proptype)| if name == prop_name { Some(proptype) } else { None })
|
||||
.ok_or(())
|
||||
.map_err(|_| {
|
||||
napi::Error::from_reason(format!(
|
||||
"Property {prop_name} of global {global_name} not found in the component"
|
||||
))
|
||||
})?;
|
||||
|
||||
self.inner
|
||||
.set_global_property(
|
||||
global_name.as_str(),
|
||||
&prop_name,
|
||||
super::value::to_value(&env, js_value, &ty)?,
|
||||
)
|
||||
.map_err(|e| Error::from_reason(format!("{e}")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn set_callback(
|
||||
&self,
|
||||
env: Env,
|
||||
callback_name: String,
|
||||
callback: JsFunction,
|
||||
) -> Result<()> {
|
||||
let function_ref = RefCountedReference::new(&env, callback)?;
|
||||
|
||||
let ty = self
|
||||
.inner
|
||||
.definition()
|
||||
.properties_and_callbacks()
|
||||
.find_map(|(name, proptype)| if name == callback_name { Some(proptype) } else { None })
|
||||
.ok_or(())
|
||||
.map_err(|_| {
|
||||
napi::Error::from_reason(format!(
|
||||
"Callback {callback_name} not found in the component"
|
||||
))
|
||||
})?;
|
||||
|
||||
if let Type::Callback { return_type, .. } = ty {
|
||||
self.inner
|
||||
.set_callback(callback_name.as_str(), {
|
||||
let return_type = return_type.clone();
|
||||
|
||||
move |args| {
|
||||
let callback: JsFunction = function_ref.get().unwrap();
|
||||
let result = callback
|
||||
.call(
|
||||
None,
|
||||
args.iter()
|
||||
.map(|v| super::value::to_js_unknown(&env, v).unwrap())
|
||||
.collect::<Vec<JsUnknown>>()
|
||||
.as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
if let Some(return_type) = &return_type {
|
||||
super::to_value(&env, result, return_type).unwrap()
|
||||
} else {
|
||||
Value::Void
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|_| napi::Error::from_reason("Cannot set callback."))?;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(napi::Error::from_reason(format!("{} is not a callback", callback_name).as_str()))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn set_global_callback(
|
||||
&self,
|
||||
env: Env,
|
||||
global_name: String,
|
||||
callback_name: String,
|
||||
callback: JsFunction,
|
||||
) -> Result<()> {
|
||||
let function_ref = RefCountedReference::new(&env, callback)?;
|
||||
|
||||
let ty = self
|
||||
.inner
|
||||
.definition()
|
||||
.global_properties_and_callbacks(global_name.as_str())
|
||||
.ok_or(napi::Error::from_reason(format!("Global {global_name} not found")))?
|
||||
.find_map(|(name, proptype)| if name == callback_name { Some(proptype) } else { None })
|
||||
.ok_or(())
|
||||
.map_err(|_| {
|
||||
napi::Error::from_reason(format!(
|
||||
"Callback {callback_name} of global {global_name} not found in the component"
|
||||
))
|
||||
})?;
|
||||
|
||||
if let Type::Callback { return_type, .. } = ty {
|
||||
self.inner
|
||||
.set_global_callback(global_name.as_str(), callback_name.as_str(), {
|
||||
let return_type = return_type.clone();
|
||||
|
||||
move |args| {
|
||||
let callback: JsFunction = function_ref.get().unwrap();
|
||||
let result = callback
|
||||
.call(
|
||||
None,
|
||||
args.iter()
|
||||
.map(|v| super::value::to_js_unknown(&env, v).unwrap())
|
||||
.collect::<Vec<JsUnknown>>()
|
||||
.as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
if let Some(return_type) = &return_type {
|
||||
super::to_value(&env, result, return_type).unwrap()
|
||||
} else {
|
||||
Value::Void
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|_| napi::Error::from_reason("Cannot set callback."))?;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(napi::Error::from_reason(format!("{} is not a callback", callback_name).as_str()))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn invoke(
|
||||
&self,
|
||||
env: Env,
|
||||
callback_name: String,
|
||||
arguments: Vec<JsUnknown>,
|
||||
) -> Result<JsUnknown> {
|
||||
let ty = self
|
||||
.inner
|
||||
.definition()
|
||||
.properties_and_callbacks()
|
||||
.find_map(|(name, proptype)| if name == callback_name { Some(proptype) } else { None })
|
||||
.ok_or(())
|
||||
.map_err(|_| {
|
||||
napi::Error::from_reason(
|
||||
format!("Callback {} not found in the component", callback_name).as_str(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let args = match ty {
|
||||
Type::Callback { args, .. } | Type::Function { args, .. } => {
|
||||
let count = args.len();
|
||||
let args = arguments
|
||||
.into_iter()
|
||||
.zip(args.into_iter())
|
||||
.map(|(a, ty)| super::value::to_value(&env, a, &ty))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
if args.len() != count {
|
||||
return Err(napi::Error::from_reason(
|
||||
format!(
|
||||
"{} expect {} arguments, but {} where provided",
|
||||
callback_name,
|
||||
count,
|
||||
args.len()
|
||||
)
|
||||
.as_str(),
|
||||
));
|
||||
}
|
||||
args
|
||||
}
|
||||
_ => {
|
||||
return Err(napi::Error::from_reason(
|
||||
format!("{} is not a callback or a function", callback_name).as_str(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let result = self
|
||||
.inner
|
||||
.invoke(callback_name.as_str(), args.as_slice())
|
||||
.map_err(|_| napi::Error::from_reason("Cannot invoke callback."))?;
|
||||
super::to_js_unknown(&env, &result)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn invoke_global(
|
||||
&self,
|
||||
env: Env,
|
||||
global_name: String,
|
||||
callback_name: String,
|
||||
arguments: Vec<JsUnknown>,
|
||||
) -> Result<JsUnknown> {
|
||||
let ty = self
|
||||
.inner
|
||||
.definition()
|
||||
.global_properties_and_callbacks(global_name.as_str())
|
||||
.ok_or(napi::Error::from_reason(format!("Global {global_name} not found")))?
|
||||
.find_map(|(name, proptype)| if name == callback_name { Some(proptype) } else { None })
|
||||
.ok_or(())
|
||||
.map_err(|_| {
|
||||
napi::Error::from_reason(
|
||||
format!(
|
||||
"Callback {} of global {global_name} not found in the component",
|
||||
callback_name
|
||||
)
|
||||
.as_str(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let args = match ty {
|
||||
Type::Callback { args, .. } | Type::Function { args, .. } => {
|
||||
let count = args.len();
|
||||
let args = arguments
|
||||
.into_iter()
|
||||
.zip(args.into_iter())
|
||||
.map(|(a, ty)| super::value::to_value(&env, a, &ty))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
if args.len() != count {
|
||||
return Err(napi::Error::from_reason(
|
||||
format!(
|
||||
"{} expect {} arguments, but {} where provided",
|
||||
callback_name,
|
||||
count,
|
||||
args.len()
|
||||
)
|
||||
.as_str(),
|
||||
));
|
||||
}
|
||||
args
|
||||
}
|
||||
_ => {
|
||||
return Err(napi::Error::from_reason(
|
||||
format!(
|
||||
"{} is not a callback or a function on global {}",
|
||||
callback_name, global_name
|
||||
)
|
||||
.as_str(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let result = self
|
||||
.inner
|
||||
.invoke_global(global_name.as_str(), callback_name.as_str(), args.as_slice())
|
||||
.map_err(|_| napi::Error::from_reason("Cannot invoke callback."))?;
|
||||
super::to_js_unknown(&env, &result)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn send_mouse_click(&self, x: f64, y: f64) {
|
||||
slint_interpreter::testing::send_mouse_click(&self.inner, x as f32, y as f32);
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn send_keyboard_string_sequence(&self, sequence: String) {
|
||||
slint_interpreter::testing::send_keyboard_string_sequence(&self.inner, sequence.into());
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn window(&self) -> Result<JsWindow> {
|
||||
Ok(JsWindow { inner: WindowInner::from_pub(self.inner.window()).window_adapter() })
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapper around Ref<>, which requires manual ref-counting.
|
||||
pub struct RefCountedReference {
|
||||
env: Env,
|
||||
reference: Ref<()>,
|
||||
}
|
||||
|
||||
impl RefCountedReference {
|
||||
pub fn new<T: NapiRaw>(env: &Env, value: T) -> Result<Self> {
|
||||
Ok(Self { env: env.clone(), reference: env.create_reference(value)? })
|
||||
}
|
||||
|
||||
pub fn get<T: NapiValue>(&self) -> Result<T> {
|
||||
self.env.get_reference_value(&self.reference)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RefCountedReference {
|
||||
fn drop(&mut self) {
|
||||
self.reference.unref(self.env).unwrap();
|
||||
}
|
||||
}
|
61
api/node/rust/interpreter/diagnostic.rs
Normal file
61
api/node/rust/interpreter/diagnostic.rs
Normal file
|
@ -0,0 +1,61 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use slint_interpreter::{Diagnostic, DiagnosticLevel};
|
||||
|
||||
/// This enum describes the level or severity of a diagnostic message produced by the compiler.
|
||||
#[napi(js_name = "DiagnosticLevel")]
|
||||
pub enum JsDiagnosticLevel {
|
||||
/// The diagnostic found is an error that prevents successful compilation.
|
||||
Error,
|
||||
|
||||
/// The diagnostic found is a warning.
|
||||
Warning,
|
||||
}
|
||||
|
||||
impl From<DiagnosticLevel> for JsDiagnosticLevel {
|
||||
fn from(diagnostic_level: DiagnosticLevel) -> Self {
|
||||
match diagnostic_level {
|
||||
DiagnosticLevel::Warning => JsDiagnosticLevel::Warning,
|
||||
_ => JsDiagnosticLevel::Error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This structure represent a diagnostic emitted while compiling .slint code.
|
||||
///
|
||||
/// It is basically a message, a level (warning or error), attached to a
|
||||
/// position in the code.
|
||||
#[napi(object, js_name = "Diagnostic")]
|
||||
pub struct JsDiagnostic {
|
||||
/// The level for this diagnostic.
|
||||
pub level: JsDiagnosticLevel,
|
||||
|
||||
/// Message for this diagnostic.
|
||||
pub message: String,
|
||||
|
||||
/// The line number in the .slint source file. The line number starts with 1.
|
||||
pub line_number: u32,
|
||||
|
||||
// The column in the .slint source file. The column number starts with 1.
|
||||
pub column_number: u32,
|
||||
|
||||
/// The path of the source file where this diagnostic occurred.
|
||||
pub file_name: Option<String>,
|
||||
}
|
||||
|
||||
impl From<Diagnostic> for JsDiagnostic {
|
||||
fn from(internal_diagnostic: Diagnostic) -> Self {
|
||||
let (line_number, column) = internal_diagnostic.line_column();
|
||||
Self {
|
||||
level: internal_diagnostic.level().into(),
|
||||
message: internal_diagnostic.message().into(),
|
||||
line_number: line_number as u32,
|
||||
column_number: column as u32,
|
||||
file_name: internal_diagnostic
|
||||
.source_file()
|
||||
.and_then(|path| path.to_str())
|
||||
.map(|str| str.into()),
|
||||
}
|
||||
}
|
||||
}
|
296
api/node/rust/interpreter/value.rs
Normal file
296
api/node/rust/interpreter/value.rs
Normal file
|
@ -0,0 +1,296 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use crate::{
|
||||
js_into_rust_model, rust_into_js_model, ReadOnlyRustModel, RgbaColor, SlintBrush,
|
||||
SlintImageData,
|
||||
};
|
||||
use i_slint_compiler::langtype::Type;
|
||||
use i_slint_core::graphics::{Image, Rgba8Pixel, SharedPixelBuffer};
|
||||
use i_slint_core::model::{ModelRc, SharedVectorModel};
|
||||
use i_slint_core::{Brush, Color, SharedVector};
|
||||
use napi::bindgen_prelude::*;
|
||||
use napi::{Env, JsBoolean, JsNumber, JsObject, JsString, JsUnknown, Result};
|
||||
use napi_derive::napi;
|
||||
use slint_interpreter::Value;
|
||||
|
||||
#[napi(js_name = "ValueType")]
|
||||
pub enum JsValueType {
|
||||
Void,
|
||||
Number,
|
||||
String,
|
||||
Bool,
|
||||
Model,
|
||||
Struct,
|
||||
Brush,
|
||||
Image,
|
||||
}
|
||||
|
||||
impl From<slint_interpreter::ValueType> for JsValueType {
|
||||
fn from(value_type: slint_interpreter::ValueType) -> Self {
|
||||
match value_type {
|
||||
slint_interpreter::ValueType::Number => JsValueType::Number,
|
||||
slint_interpreter::ValueType::String => JsValueType::String,
|
||||
slint_interpreter::ValueType::Bool => JsValueType::Bool,
|
||||
slint_interpreter::ValueType::Model => JsValueType::Model,
|
||||
slint_interpreter::ValueType::Struct => JsValueType::Struct,
|
||||
slint_interpreter::ValueType::Brush => JsValueType::Brush,
|
||||
slint_interpreter::ValueType::Image => JsValueType::Image,
|
||||
_ => JsValueType::Void,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "Property")]
|
||||
pub struct JsProperty {
|
||||
pub name: String,
|
||||
pub value_type: JsValueType,
|
||||
}
|
||||
|
||||
pub fn to_js_unknown(env: &Env, value: &Value) -> Result<JsUnknown> {
|
||||
match value {
|
||||
Value::Void => env.get_null().map(|v| v.into_unknown()),
|
||||
Value::Number(number) => env.create_double(*number).map(|v| v.into_unknown()),
|
||||
Value::String(string) => env.create_string(string).map(|v| v.into_unknown()),
|
||||
Value::Bool(value) => env.get_boolean(*value).map(|v| v.into_unknown()),
|
||||
Value::Image(image) => Ok(SlintImageData::from(image.clone())
|
||||
.into_instance(*env)?
|
||||
.as_object(*env)
|
||||
.into_unknown()),
|
||||
Value::Struct(struct_value) => {
|
||||
let mut o = env.create_object()?;
|
||||
for (field_name, field_value) in struct_value.iter() {
|
||||
o.set_property(
|
||||
env.create_string(&field_name.replace('-', "_"))?,
|
||||
to_js_unknown(env, field_value)?,
|
||||
)?;
|
||||
}
|
||||
Ok(o.into_unknown())
|
||||
}
|
||||
Value::Brush(brush) => {
|
||||
Ok(SlintBrush::from(brush.clone()).into_instance(*env)?.as_object(*env).into_unknown())
|
||||
}
|
||||
Value::Model(model) => {
|
||||
if let Some(maybe_js_model) = rust_into_js_model(model) {
|
||||
maybe_js_model
|
||||
} else {
|
||||
let model_wrapper: ReadOnlyRustModel = model.clone().into();
|
||||
model_wrapper.into_js(env)
|
||||
}
|
||||
}
|
||||
_ => env.get_undefined().map(|v| v.into_unknown()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_value(env: &Env, unknown: JsUnknown, typ: &Type) -> Result<Value> {
|
||||
match typ {
|
||||
Type::Float32
|
||||
| Type::Int32
|
||||
| Type::Duration
|
||||
| Type::Angle
|
||||
| Type::PhysicalLength
|
||||
| Type::LogicalLength
|
||||
| Type::Rem
|
||||
| Type::Percent
|
||||
| Type::UnitProduct(_) => {
|
||||
let js_number: Result<JsNumber> = unknown.try_into();
|
||||
Ok(Value::Number(js_number?.get_double()?))
|
||||
}
|
||||
Type::String => {
|
||||
let js_string: JsString = unknown.try_into()?;
|
||||
Ok(Value::String(js_string.into_utf8()?.as_str()?.into()))
|
||||
}
|
||||
Type::Bool => {
|
||||
let js_bool: JsBoolean = unknown.try_into()?;
|
||||
Ok(Value::Bool(js_bool.get_value()?))
|
||||
}
|
||||
Type::Color => {
|
||||
match unknown.get_type() {
|
||||
Ok(ValueType::String) => {
|
||||
return Ok(unknown.coerce_to_string().and_then(|str| string_to_brush(str))?);
|
||||
}
|
||||
Ok(ValueType::Object) => {
|
||||
if let Ok(rgb_color) = unknown.coerce_to_object() {
|
||||
return brush_from_color(rgb_color);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Err(napi::Error::from_reason(
|
||||
"Cannot convert object to brush, because the given object is neither a brush, color, nor a string".to_string()
|
||||
))
|
||||
}
|
||||
Type::Brush => {
|
||||
match unknown.get_type() {
|
||||
Ok(ValueType::String) => {
|
||||
return Ok(unknown.coerce_to_string().and_then(|str| string_to_brush(str))?);
|
||||
}
|
||||
Ok(ValueType::Object) => {
|
||||
if let Ok(obj) = unknown.coerce_to_object() {
|
||||
// this is used to make the color property of the `Brush` interface optional.
|
||||
let properties = obj.get_property_names()?;
|
||||
if properties.get_array_length()? == 0 {
|
||||
return Ok(Value::Brush(Brush::default()));
|
||||
}
|
||||
if let Some(color) = obj.get::<&str, RgbaColor>("color").ok().flatten() {
|
||||
if color.red() < 0.
|
||||
|| color.green() < 0.
|
||||
|| color.blue() < 0.
|
||||
|| color.alpha() < 0.
|
||||
{
|
||||
return Err(Error::from_reason(
|
||||
"A channel of Color cannot be negative",
|
||||
));
|
||||
}
|
||||
|
||||
return Ok(Value::Brush(Brush::SolidColor(Color::from_argb_u8(
|
||||
color.alpha() as u8,
|
||||
color.red() as u8,
|
||||
color.green() as u8,
|
||||
color.blue() as u8,
|
||||
))));
|
||||
} else {
|
||||
return brush_from_color(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Err(napi::Error::from_reason(
|
||||
"Cannot convert object to brush, because the given object is neither a brush, color, nor a string".to_string()
|
||||
))
|
||||
}
|
||||
Type::Image => {
|
||||
let object = unknown.coerce_to_object()?;
|
||||
if let Some(direct_image) = object.get("image").ok().flatten() {
|
||||
Ok(Value::Image(env.get_value_external::<Image>(&direct_image)?.clone()))
|
||||
} else {
|
||||
let get_size_prop = |name| {
|
||||
object
|
||||
.get::<_, JsUnknown>(name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|prop| prop.coerce_to_number().ok())
|
||||
.and_then(|number| number.get_int64().ok())
|
||||
.and_then(|i64_num| i64_num.try_into().ok())
|
||||
.ok_or_else(
|
||||
|| napi::Error::from_reason(
|
||||
format!("Cannot convert object to image, because the provided object does not have an u32 `{name}` property")
|
||||
))
|
||||
};
|
||||
|
||||
fn try_convert_image<BufferType: AsRef<[u8]> + FromNapiValue>(
|
||||
object: &JsObject,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Result<SharedPixelBuffer<Rgba8Pixel>> {
|
||||
let buffer =
|
||||
object.get::<_, BufferType>("data").ok().flatten().ok_or_else(|| {
|
||||
napi::Error::from_reason(
|
||||
"data property does not have suitable array buffer type"
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
const BPP: usize = core::mem::size_of::<Rgba8Pixel>();
|
||||
let actual_size = buffer.as_ref().len();
|
||||
let expected_size: usize = (width as usize) * (height as usize) * BPP;
|
||||
if actual_size != expected_size {
|
||||
return Err(napi::Error::from_reason(format!(
|
||||
"data property does not have the correct size; expected {} (width) * {} (height) * {} = {}; got {}",
|
||||
width, height, BPP, actual_size, expected_size
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(SharedPixelBuffer::clone_from_slice(buffer.as_ref(), width, height))
|
||||
}
|
||||
|
||||
let width: u32 = get_size_prop("width")?;
|
||||
let height: u32 = get_size_prop("height")?;
|
||||
|
||||
let pixel_buffer =
|
||||
try_convert_image::<Uint8ClampedArray>(&object, width, height)
|
||||
.or_else(|_| try_convert_image::<Buffer>(&object, width, height))?;
|
||||
|
||||
Ok(Value::Image(Image::from_rgba8(pixel_buffer)))
|
||||
}
|
||||
}
|
||||
Type::Struct { fields, name: _, node: _, rust_attributes: _ } => {
|
||||
let js_object = unknown.coerce_to_object()?;
|
||||
|
||||
Ok(Value::Struct(
|
||||
fields
|
||||
.iter()
|
||||
.map(|(pro_name, pro_ty)| {
|
||||
let prop: JsUnknown = js_object
|
||||
.get_property(env.create_string(&pro_name.replace('-', "_"))?)?;
|
||||
let prop_value = if prop.get_type()? == napi::ValueType::Undefined {
|
||||
slint_interpreter::default_value_for_type(pro_ty)
|
||||
} else {
|
||||
to_value(env, prop, pro_ty)?
|
||||
};
|
||||
Ok((pro_name.clone(), prop_value))
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
))
|
||||
}
|
||||
Type::Array(a) => {
|
||||
if unknown.is_array()? {
|
||||
let array = Array::from_unknown(unknown)?;
|
||||
let mut vec = vec![];
|
||||
|
||||
for i in 0..array.len() {
|
||||
vec.push(to_value(env, array.get(i)?.unwrap(), a)?);
|
||||
}
|
||||
Ok(Value::Model(ModelRc::new(SharedVectorModel::from(SharedVector::from_slice(
|
||||
&vec,
|
||||
)))))
|
||||
} else {
|
||||
let rust_model =
|
||||
unknown.coerce_to_object().and_then(|obj| js_into_rust_model(env, &obj, &a))?;
|
||||
Ok(Value::Model(rust_model))
|
||||
}
|
||||
}
|
||||
Type::Enumeration(_) => todo!(),
|
||||
Type::Invalid
|
||||
| Type::Model
|
||||
| Type::Void
|
||||
| Type::InferredProperty
|
||||
| Type::InferredCallback
|
||||
| Type::Function { .. }
|
||||
| Type::Callback { .. }
|
||||
| Type::ComponentFactory { .. }
|
||||
| Type::Easing
|
||||
| Type::PathData
|
||||
| Type::LayoutCache
|
||||
| Type::ElementReference => Err(napi::Error::from_reason("reason")),
|
||||
}
|
||||
}
|
||||
|
||||
fn string_to_brush(js_string: JsString) -> Result<Value> {
|
||||
let string = js_string.into_utf8()?.as_str()?.to_string();
|
||||
|
||||
let c = string
|
||||
.parse::<css_color_parser2::Color>()
|
||||
.map_err(|_| napi::Error::from_reason(format!("Could not convert {string} to Brush.")))?;
|
||||
|
||||
Ok(Value::Brush(Brush::from(Color::from_argb_u8((c.a * 255.) as u8, c.r, c.g, c.b)).into()))
|
||||
}
|
||||
|
||||
fn brush_from_color(rgb_color: Object) -> Result<Value> {
|
||||
let red: f64 = rgb_color.get("red")?.ok_or(Error::from_reason("Property red is missing"))?;
|
||||
let green: f64 =
|
||||
rgb_color.get("green")?.ok_or(Error::from_reason("Property green is missing"))?;
|
||||
let blue: f64 = rgb_color.get("blue")?.ok_or(Error::from_reason("Property blue is missing"))?;
|
||||
let alpha: f64 = rgb_color.get("alpha")?.unwrap_or(255.);
|
||||
|
||||
if red < 0. || green < 0. || blue < 0. || alpha < 0. {
|
||||
return Err(Error::from_reason("A channel of Color cannot be negative"));
|
||||
}
|
||||
|
||||
return Ok(Value::Brush(Brush::SolidColor(Color::from_argb_u8(
|
||||
alpha as u8,
|
||||
red as u8,
|
||||
green as u8,
|
||||
blue as u8,
|
||||
))));
|
||||
}
|
162
api/node/rust/interpreter/window.rs
Normal file
162
api/node/rust/interpreter/window.rs
Normal file
|
@ -0,0 +1,162 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use crate::types::{SlintPoint, SlintSize};
|
||||
use i_slint_core::window::WindowAdapterRc;
|
||||
use slint_interpreter::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize};
|
||||
|
||||
/// This type represents a window towards the windowing system, that's used to render the
|
||||
/// scene of a component. It provides API to control windowing system specific aspects such
|
||||
/// as the position on the screen.
|
||||
#[napi(js_name = "Window")]
|
||||
pub struct JsWindow {
|
||||
pub(crate) inner: WindowAdapterRc,
|
||||
}
|
||||
|
||||
impl From<WindowAdapterRc> for JsWindow {
|
||||
fn from(instance: WindowAdapterRc) -> Self {
|
||||
Self { inner: instance }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl JsWindow {
|
||||
/// @hidden
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> napi::Result<Self> {
|
||||
Err(napi::Error::from_reason(
|
||||
"Window can only be created by using a Component.".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Shows the window on the screen. An additional strong reference on the
|
||||
/// associated component is maintained while the window is visible.
|
||||
#[napi]
|
||||
pub fn show(&self) -> napi::Result<()> {
|
||||
self.inner
|
||||
.window()
|
||||
.show()
|
||||
.map_err(|_| napi::Error::from_reason("Cannot show window.".to_string()))
|
||||
}
|
||||
|
||||
/// Hides the window, so that it is not visible anymore.
|
||||
#[napi]
|
||||
pub fn hide(&self) -> napi::Result<()> {
|
||||
self.inner
|
||||
.window()
|
||||
.hide()
|
||||
.map_err(|_| napi::Error::from_reason("Cannot hide window.".to_string()))
|
||||
}
|
||||
|
||||
/// Returns the visibility state of the window. This function can return false even if you previously called show()
|
||||
/// on it, for example if the user minimized the window.
|
||||
#[napi(getter, js_name = "visible")]
|
||||
pub fn is_visible(&self) -> bool {
|
||||
self.inner.window().is_visible()
|
||||
}
|
||||
|
||||
/// Returns the logical position of the window on the screen.
|
||||
#[napi(getter)]
|
||||
pub fn get_logical_position(&self) -> SlintPoint {
|
||||
let pos = self.inner.window().position().to_logical(self.inner.window().scale_factor());
|
||||
SlintPoint { x: pos.x as f64, y: pos.y as f64 }
|
||||
}
|
||||
|
||||
/// Sets the logical position of the window on the screen.
|
||||
#[napi(setter)]
|
||||
pub fn set_logical_position(&self, position: SlintPoint) {
|
||||
self.inner
|
||||
.window()
|
||||
.set_position(LogicalPosition { x: position.x as f32, y: position.y as f32 });
|
||||
}
|
||||
|
||||
/// Returns the physical position of the window on the screen.
|
||||
#[napi(getter)]
|
||||
pub fn get_physical_position(&self) -> SlintPoint {
|
||||
let pos = self.inner.window().position();
|
||||
SlintPoint { x: pos.x as f64, y: pos.y as f64 }
|
||||
}
|
||||
|
||||
/// Sets the physical position of the window on the screen.
|
||||
#[napi(setter)]
|
||||
pub fn set_physical_position(&self, position: SlintPoint) {
|
||||
self.inner.window().set_position(PhysicalPosition {
|
||||
x: position.x.floor() as i32,
|
||||
y: position.y.floor() as i32,
|
||||
});
|
||||
}
|
||||
|
||||
/// Returns the logical size of the window on the screen,
|
||||
#[napi(getter)]
|
||||
pub fn get_logical_size(&self) -> SlintSize {
|
||||
let size = self.inner.window().size().to_logical(self.inner.window().scale_factor());
|
||||
SlintSize { width: size.width as f64, height: size.height as f64 }
|
||||
}
|
||||
|
||||
/// Sets the logical size of the window on the screen,
|
||||
#[napi(setter)]
|
||||
pub fn set_logical_size(&self, size: SlintSize) {
|
||||
self.inner.window().set_size(LogicalSize::from_physical(
|
||||
PhysicalSize { width: size.width.floor() as u32, height: size.height.floor() as u32 },
|
||||
self.inner.window().scale_factor(),
|
||||
));
|
||||
}
|
||||
|
||||
/// Returns the physical size of the window on the screen,
|
||||
#[napi(getter)]
|
||||
pub fn get_physical_size(&self) -> SlintSize {
|
||||
let size = self.inner.window().size();
|
||||
SlintSize { width: size.width as f64, height: size.height as f64 }
|
||||
}
|
||||
|
||||
/// Sets the logical size of the window on the screen,
|
||||
#[napi(setter)]
|
||||
pub fn set_physical_size(&self, size: SlintSize) {
|
||||
self.inner.window().set_size(PhysicalSize {
|
||||
width: size.width.floor() as u32,
|
||||
height: size.height.floor() as u32,
|
||||
});
|
||||
}
|
||||
|
||||
/// Issues a request to the windowing system to re-render the contents of the window.
|
||||
#[napi(js_name = "requestRedraw")]
|
||||
pub fn request_redraw(&self) {
|
||||
self.inner.request_redraw();
|
||||
}
|
||||
|
||||
/// Returns if the window is currently fullscreen
|
||||
#[napi(getter)]
|
||||
pub fn get_fullscreen(&self) -> bool {
|
||||
self.inner.window().is_fullscreen()
|
||||
}
|
||||
|
||||
/// Set or unset the window to display fullscreen.
|
||||
#[napi(setter)]
|
||||
pub fn set_fullscreen(&self, enable: bool) {
|
||||
self.inner.window().set_fullscreen(enable)
|
||||
}
|
||||
|
||||
/// Returns if the window is currently maximized
|
||||
#[napi(getter)]
|
||||
pub fn get_maximized(&self) -> bool {
|
||||
self.inner.window().is_maximized()
|
||||
}
|
||||
|
||||
/// Maximize or unmaximize the window.
|
||||
#[napi(setter)]
|
||||
pub fn set_maximized(&self, maximized: bool) {
|
||||
self.inner.window().set_maximized(maximized)
|
||||
}
|
||||
|
||||
/// Returns if the window is currently minimized
|
||||
#[napi(getter)]
|
||||
pub fn get_minimized(&self) -> bool {
|
||||
self.inner.window().is_minimized()
|
||||
}
|
||||
|
||||
/// Minimize or unminimze the window.
|
||||
#[napi(setter)]
|
||||
pub fn set_minimized(&self, minimized: bool) {
|
||||
self.inner.window().set_minimized(minimized)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue