| 1 | // Copyright © SixtyFPS GmbH <info@slint.dev> |
| 2 | // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0 |
| 3 | |
| 4 | use crate::to_js_unknown; |
| 5 | use crate::RefCountedReference; |
| 6 | |
| 7 | use super::JsComponentDefinition; |
| 8 | use super::JsDiagnostic; |
| 9 | use i_slint_compiler::langtype::Type; |
| 10 | use itertools::Itertools; |
| 11 | use napi::Env; |
| 12 | use napi::JsFunction; |
| 13 | use napi::JsString; |
| 14 | use napi::JsUnknown; |
| 15 | use slint_interpreter::Compiler; |
| 16 | use slint_interpreter::Value; |
| 17 | use smol_str::StrExt; |
| 18 | use std::collections::HashMap; |
| 19 | use std::path::PathBuf; |
| 20 | |
| 21 | /// ComponentCompiler is the entry point to the Slint interpreter that can be used |
| 22 | /// to load .slint files or compile them on-the-fly from a string. |
| 23 | #[napi (js_name = "ComponentCompiler" )] |
| 24 | pub struct JsComponentCompiler { |
| 25 | internal: Compiler, |
| 26 | structs_and_enums: Vec<Type>, |
| 27 | diagnostics: Vec<slint_interpreter::Diagnostic>, |
| 28 | } |
| 29 | |
| 30 | #[napi ] |
| 31 | impl JsComponentCompiler { |
| 32 | /// Returns a new ComponentCompiler. |
| 33 | #[napi (constructor)] |
| 34 | pub fn new() -> Self { |
| 35 | let mut compiler = Compiler::default(); |
| 36 | let include_paths = match std::env::var_os("SLINT_INCLUDE_PATH" ) { |
| 37 | Some(paths) => { |
| 38 | std::env::split_paths(&paths).filter(|path| !path.as_os_str().is_empty()).collect() |
| 39 | } |
| 40 | None => vec![], |
| 41 | }; |
| 42 | let library_paths = match std::env::var_os("SLINT_LIBRARY_PATH" ) { |
| 43 | Some(paths) => std::env::split_paths(&paths) |
| 44 | .filter_map(|entry| { |
| 45 | entry |
| 46 | .to_str() |
| 47 | .unwrap_or_default() |
| 48 | .split('=' ) |
| 49 | .collect_tuple() |
| 50 | .map(|(k, v)| (k.into(), v.into())) |
| 51 | }) |
| 52 | .collect(), |
| 53 | None => HashMap::new(), |
| 54 | }; |
| 55 | |
| 56 | compiler.set_include_paths(include_paths); |
| 57 | compiler.set_library_paths(library_paths); |
| 58 | Self { internal: compiler, diagnostics: vec![], structs_and_enums: vec![] } |
| 59 | } |
| 60 | |
| 61 | #[napi (setter)] |
| 62 | pub fn set_include_paths(&mut self, include_paths: Vec<String>) { |
| 63 | self.internal.set_include_paths(include_paths.iter().map(|p| PathBuf::from(p)).collect()); |
| 64 | } |
| 65 | |
| 66 | #[napi (getter)] |
| 67 | pub fn include_paths(&self) -> Vec<String> { |
| 68 | self.internal |
| 69 | .include_paths() |
| 70 | .iter() |
| 71 | .map(|p| p.to_str().unwrap_or_default().to_string()) |
| 72 | .collect() |
| 73 | } |
| 74 | |
| 75 | #[napi (setter)] |
| 76 | pub fn set_library_paths(&mut self, paths: HashMap<String, String>) { |
| 77 | let mut library_paths = HashMap::new(); |
| 78 | for (key, path) in paths { |
| 79 | library_paths.insert(key, PathBuf::from(path)); |
| 80 | } |
| 81 | |
| 82 | self.internal.set_library_paths(library_paths); |
| 83 | } |
| 84 | |
| 85 | #[napi (getter)] |
| 86 | pub fn library_paths(&self) -> HashMap<String, String> { |
| 87 | let mut library_paths = HashMap::new(); |
| 88 | |
| 89 | for (key, path) in self.internal.library_paths() { |
| 90 | library_paths.insert(key.clone(), path.to_str().unwrap_or_default().to_string()); |
| 91 | } |
| 92 | |
| 93 | library_paths |
| 94 | } |
| 95 | |
| 96 | #[napi (setter)] |
| 97 | pub fn set_style(&mut self, style: String) { |
| 98 | self.internal.set_style(style); |
| 99 | } |
| 100 | |
| 101 | #[napi (getter)] |
| 102 | pub fn style(&self) -> Option<String> { |
| 103 | self.internal.style().cloned() |
| 104 | } |
| 105 | |
| 106 | // todo: set_file_loader |
| 107 | |
| 108 | #[napi (getter)] |
| 109 | pub fn diagnostics(&self) -> Vec<JsDiagnostic> { |
| 110 | self.diagnostics.iter().map(|d| JsDiagnostic::from(d.clone())).collect() |
| 111 | } |
| 112 | |
| 113 | #[napi (getter)] |
| 114 | pub fn structs(&self, env: Env) -> HashMap<String, JsUnknown> { |
| 115 | fn convert_type(env: &Env, ty: &Type) -> Option<(String, JsUnknown)> { |
| 116 | match ty { |
| 117 | Type::Struct(s) if s.name.is_some() && s.node.is_some() => { |
| 118 | let name = s.name.as_ref().unwrap(); |
| 119 | let struct_instance = to_js_unknown( |
| 120 | env, |
| 121 | &Value::Struct(slint_interpreter::Struct::from_iter(s.fields.iter().map( |
| 122 | |(name, field_type)| { |
| 123 | ( |
| 124 | name.to_string(), |
| 125 | slint_interpreter::default_value_for_type(field_type), |
| 126 | ) |
| 127 | }, |
| 128 | ))), |
| 129 | ); |
| 130 | |
| 131 | Some((name.to_string(), struct_instance.ok()?)) |
| 132 | } |
| 133 | _ => None, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | self.structs_and_enums |
| 138 | .iter() |
| 139 | .filter_map(|ty| convert_type(&env, ty)) |
| 140 | .into_iter() |
| 141 | .collect::<HashMap<String, JsUnknown>>() |
| 142 | } |
| 143 | |
| 144 | #[napi (getter)] |
| 145 | pub fn enums(&self, env: Env) -> HashMap<String, JsUnknown> { |
| 146 | fn convert_type(env: &Env, ty: &Type) -> Option<(String, JsUnknown)> { |
| 147 | match ty { |
| 148 | Type::Enumeration(en) => { |
| 149 | let mut o = env.create_object().ok()?; |
| 150 | |
| 151 | for value in en.values.iter() { |
| 152 | let value = value.replace_smolstr("-" , "_" ); |
| 153 | o.set_property( |
| 154 | env.create_string(&value).ok()?, |
| 155 | env.create_string(&value).ok()?.into_unknown(), |
| 156 | ) |
| 157 | .ok()?; |
| 158 | } |
| 159 | Some((en.name.to_string(), o.into_unknown())) |
| 160 | } |
| 161 | _ => None, |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | self.structs_and_enums |
| 166 | .iter() |
| 167 | .filter_map(|ty| convert_type(&env, ty)) |
| 168 | .into_iter() |
| 169 | .collect::<HashMap<String, JsUnknown>>() |
| 170 | } |
| 171 | |
| 172 | #[napi (setter)] |
| 173 | pub fn set_file_loader(&mut self, env: Env, callback: JsFunction) -> napi::Result<()> { |
| 174 | let function_ref = std::rc::Rc::new(RefCountedReference::new(&env, callback)?); |
| 175 | |
| 176 | self.internal.set_file_loader(move |path| { |
| 177 | let path = PathBuf::from(path); |
| 178 | let function_ref = function_ref.clone(); |
| 179 | Box::pin({ |
| 180 | async move { |
| 181 | let Ok(callback) = function_ref.get::<JsFunction>() else { |
| 182 | return Some(Err(std::io::Error::other( |
| 183 | "Node.js: cannot access file loader callback." , |
| 184 | ))); |
| 185 | }; |
| 186 | |
| 187 | let Ok(path) = env.create_string(path.display().to_string().as_str()) else { |
| 188 | return Some(Err(std::io::Error::other( |
| 189 | "Node.js: wrong argunemt for callback file_loader." , |
| 190 | ))); |
| 191 | }; |
| 192 | |
| 193 | let result = match callback.call(None, &[path]) { |
| 194 | Ok(result) => result, |
| 195 | Err(err) => { |
| 196 | return Some(Err(std::io::Error::other(err.to_string()))); |
| 197 | } |
| 198 | }; |
| 199 | |
| 200 | let js_string: napi::Result<JsString> = result.try_into(); |
| 201 | |
| 202 | let Ok(js_string) = js_string else { |
| 203 | return Some(Err(std::io::Error::other( |
| 204 | "Node.js: cannot read return value of file loader callback as js string." , |
| 205 | ))); |
| 206 | }; |
| 207 | |
| 208 | let Ok(utf8_string) = js_string.into_utf8() else { |
| 209 | return Some(Err(std::io::Error::other( |
| 210 | "Node.js: cannot convert return value of file loader callback into utf8." , |
| 211 | ))); |
| 212 | }; |
| 213 | |
| 214 | if let Ok(str) = utf8_string.as_str() { |
| 215 | let string = str.to_string(); |
| 216 | |
| 217 | return Some(Ok(string)); |
| 218 | }; |
| 219 | |
| 220 | Some(Err(std::io::Error::other( |
| 221 | "Node.js: cannot convert return value of file loader callback into string." , |
| 222 | ))) |
| 223 | } |
| 224 | }) |
| 225 | }); |
| 226 | |
| 227 | Ok(()) |
| 228 | } |
| 229 | |
| 230 | /// Compile a .slint file into a ComponentDefinition |
| 231 | /// |
| 232 | /// Returns the compiled `ComponentDefinition` if there were no errors. |
| 233 | #[napi ] |
| 234 | pub fn build_from_path(&mut self, path: String) -> HashMap<String, JsComponentDefinition> { |
| 235 | let r = spin_on::spin_on(self.internal.build_from_path(PathBuf::from(path))); |
| 236 | self.structs_and_enums = |
| 237 | r.structs_and_enums(i_slint_core::InternalToken {}).cloned().collect::<Vec<_>>(); |
| 238 | self.diagnostics = r.diagnostics().collect(); |
| 239 | r.components().map(|c| (c.name().to_owned(), c.into())).collect() |
| 240 | } |
| 241 | |
| 242 | /// Compile some .slint code into a ComponentDefinition |
| 243 | #[napi ] |
| 244 | pub fn build_from_source( |
| 245 | &mut self, |
| 246 | source_code: String, |
| 247 | path: String, |
| 248 | ) -> HashMap<String, JsComponentDefinition> { |
| 249 | let r = spin_on::spin_on(self.internal.build_from_source(source_code, PathBuf::from(path))); |
| 250 | self.diagnostics = r.diagnostics().collect(); |
| 251 | self.structs_and_enums = |
| 252 | r.structs_and_enums(i_slint_core::InternalToken {}).cloned().collect::<Vec<_>>(); |
| 253 | r.components().map(|c| (c.name().to_owned(), c.into())).collect() |
| 254 | } |
| 255 | } |
| 256 | |