1#[cfg(feature = "std")]
10use crate::AnimationMode;
11use crate::prelude::*;
12use crate::public_api;
13#[cfg(feature = "std")]
14use i_slint_compiler::ComponentSelection;
15#[cfg(feature = "std")]
16use i_slint_compiler::builtin_functions::BuiltinFunction;
17use i_slint_compiler::langtype::Type as LangType;
18#[cfg(feature = "std")]
19use i_slint_compiler::llr::Expression;
20use i_slint_compiler::llr::{CompilationUnit, GlobalComponent, PublicComponentIdx};
21use i_slint_compiler::names::normalize_identifier;
22use i_slint_compiler::native_class::PropertyVisibility;
23#[cfg(feature = "std")]
24use i_slint_compiler::source_path::SourcePath;
25
26#[derive(Clone, Default)]
36pub struct TypeLoaders {
37 #[cfg(feature = "std")]
38 #[cfg_attr(not(any(feature = "internal", feature = "internal-highlight")), allow(dead_code))]
39 pub type_loader: Option<Rc<i_slint_compiler::typeloader::TypeLoader>>,
40 #[cfg(feature = "std")]
41 #[cfg_attr(not(feature = "internal-highlight"), allow(dead_code))]
42 pub raw_type_loader: Option<Rc<i_slint_compiler::typeloader::TypeLoader>>,
43 #[cfg(feature = "std")]
49 pub originals: Rc<
50 typed_index_collections::TiVec<
51 PublicComponentIdx,
52 Rc<i_slint_compiler::object_tree::Component>,
53 >,
54 >,
55}
56
57#[cfg(feature = "std")]
59pub type ResourceLoader =
60 Rc<dyn Fn(SourcePath) -> Pin<Box<dyn Future<Output = std::io::Result<Vec<u8>>>>>>;
61
62pub type FontFiles = HashMap<String, alloc::sync::Arc<Vec<u8>>>;
65
66#[derive(Clone, Default)]
68pub struct Resources {
69 pub font_files: FontFiles,
70 #[cfg(feature = "internal-mcu-interpreter")]
71 pub pre_rendered: crate::static_resources::PreRendered,
72}
73
74#[derive(Clone)]
78pub struct ComponentDefinitionInner {
79 pub compilation_unit: Rc<CompilationUnit>,
80 pub public_index: PublicComponentIdx,
81 pub type_loaders: TypeLoaders,
84 pub resources: Rc<Resources>,
85}
86
87impl ComponentDefinitionInner {
88 pub fn name(&self) -> &str {
89 self.public().name.as_str()
90 }
91
92 pub fn create_with_existing_window(
95 &self,
96 window_adapter: i_slint_core::window::WindowAdapterRc,
97 ) -> ComponentInstanceInner {
98 let vrc = Instance::new_with_window(
99 self.compilation_unit.clone(),
100 self.public_index,
101 window_adapter,
102 self.type_loaders.clone(),
103 self.resources.clone(),
104 );
105 ComponentInstanceInner(vrc)
106 }
107
108 pub fn create_with_context(&self, context: SlintContext) -> ComponentInstanceInner {
110 let vrc = Instance::new_with_context(
111 self.compilation_unit.clone(),
112 self.public_index,
113 self.type_loaders.clone(),
114 self.resources.clone(),
115 context,
116 );
117 ComponentInstanceInner(vrc)
118 }
119
120 #[cfg(feature = "internal")]
121 pub fn create_detached_with_existing_window(
122 &self,
123 window_adapter: i_slint_core::window::WindowAdapterRc,
124 ) -> ComponentInstanceInner {
125 let vrc = Instance::new_detached_with_window(
126 self.compilation_unit.clone(),
127 self.public_index,
128 window_adapter,
129 self.type_loaders.clone(),
130 self.resources.clone(),
131 );
132 ComponentInstanceInner(vrc)
133 }
134
135 pub fn create_embedded(
140 &self,
141 parent: vtable::VWeak<ItemTreeVTable>,
142 parent_item_tree_index: u32,
143 ) -> ComponentInstanceInner {
144 let vrc = Instance::new_embedded(
145 self.compilation_unit.clone(),
146 self.public_index,
147 self.type_loaders.clone(),
148 self.resources.clone(),
149 parent,
150 parent_item_tree_index,
151 );
152 ComponentInstanceInner(vrc)
153 }
154
155 fn public(&self) -> &i_slint_compiler::llr::PublicComponent {
156 &self.compilation_unit.public_components[self.public_index]
157 }
158
159 #[cfg_attr(not(feature = "internal"), allow(dead_code))]
162 pub fn top_level_type(&self) -> i_slint_compiler::llr::TopLevelComponentType {
163 self.public().top_level_type
164 }
165
166 fn properties_with_info(
167 &self,
168 ) -> impl Iterator<Item = (SmolStr, LangType, PropertyVisibility)> + '_ {
169 public_properties_info(&self.public().public_properties)
170 }
171
172 #[cfg_attr(not(feature = "internal"), allow(dead_code))]
177 pub fn properties_and_callbacks(
178 &self,
179 ) -> impl Iterator<Item = (SmolStr, LangType, PropertyVisibility)> + '_ {
180 self.properties_with_info()
181 }
182
183 pub fn properties(&self) -> impl Iterator<Item = (SmolStr, LangType)> + '_ {
186 self.properties_with_info()
187 .filter(|(_, ty, _)| ty.is_property_type())
188 .map(|(n, ty, _)| (n, ty))
189 }
190
191 pub fn callbacks(&self) -> impl Iterator<Item = SmolStr> + '_ {
192 self.properties_with_info()
193 .filter(|(_, ty, _)| matches!(ty, LangType::Callback(_)))
194 .map(|(n, _, _)| n)
195 }
196
197 pub fn functions(&self) -> impl Iterator<Item = SmolStr> + '_ {
198 self.properties_with_info()
199 .filter(|(_, ty, _)| matches!(ty, LangType::Function(_)))
200 .map(|(n, _, _)| n)
201 }
202
203 pub fn globals(&self) -> impl Iterator<Item = SmolStr> + '_ {
206 self.compilation_unit
207 .globals
208 .iter()
209 .filter(|g| visible_in_public_api(g))
210 .flat_map(|g| g.aliases.iter().cloned().chain(core::iter::once(g.name.clone())))
211 }
212
213 fn global_by_name(&self, name: &str) -> Option<&GlobalComponent> {
214 let needle = normalize_identifier(name);
217 self.compilation_unit.globals.iter().filter(|g| visible_in_public_api(g)).find(|g| {
218 normalize_identifier(&g.name) == needle
219 || g.aliases.iter().any(|a| normalize_identifier(a) == needle)
220 })
221 }
222
223 pub fn global_properties_and_callbacks(
224 &self,
225 name: &str,
226 ) -> Option<impl Iterator<Item = (SmolStr, LangType, PropertyVisibility)> + '_> {
227 self.global_by_name(name).map(|g| public_properties_info(&g.public_properties))
228 }
229
230 pub fn global_properties(
231 &self,
232 name: &str,
233 ) -> Option<impl Iterator<Item = (SmolStr, LangType)> + '_> {
234 self.global_properties_and_callbacks(name)
235 .map(|it| it.filter(|(_, ty, _)| ty.is_property_type()).map(|(n, ty, _)| (n, ty)))
236 }
237
238 pub fn global_callbacks(&self, name: &str) -> Option<impl Iterator<Item = SmolStr> + '_> {
239 self.global_properties_and_callbacks(name).map(|it| {
240 it.filter(|(_, ty, _)| matches!(ty, LangType::Callback(_))).map(|(n, _, _)| n)
241 })
242 }
243
244 pub fn global_functions(&self, name: &str) -> Option<impl Iterator<Item = SmolStr> + '_> {
245 self.global_properties_and_callbacks(name).map(|it| {
246 it.filter(|(_, ty, _)| matches!(ty, LangType::Function(_))).map(|(n, _, _)| n)
247 })
248 }
249}
250
251fn public_properties_info<'a>(
252 public_properties: &'a i_slint_compiler::llr::PublicProperties,
253) -> impl Iterator<Item = (SmolStr, LangType, PropertyVisibility)> + 'a {
254 public_properties.values().map(|p| (p.display_name.clone(), p.ty.clone(), p.visibility))
257}
258
259fn visible_in_public_api(g: &GlobalComponent) -> bool {
260 g.exported && !g.is_builtin
262}
263
264#[repr(transparent)]
269pub struct ComponentInstanceInner(pub VRc<ItemTreeVTable, Instance>);
270
271impl Clone for ComponentInstanceInner {
272 fn clone(&self) -> Self {
273 Self(self.0.clone())
274 }
275}
276
277impl ComponentInstanceInner {
278 pub fn vrc(&self) -> &VRc<ItemTreeVTable, Instance> {
281 &self.0
282 }
283
284 pub fn get_property(&self, name: &str) -> Option<Value> {
285 public_api::get(&self.0, name)
286 }
287
288 pub fn set_property(
289 &self,
290 name: &str,
291 value: Value,
292 ) -> Result<(), crate::api::SetPropertyError> {
293 public_api::set(&self.0, name, value)
294 }
295
296 pub fn invoke(&self, name: &str, args: &[Value]) -> Option<Value> {
297 public_api::invoke(&self.0, name, args)
298 }
299
300 pub fn set_callback(
301 &self,
302 name: &str,
303 handler: impl Fn(&[Value]) -> Value + 'static,
304 ) -> Result<(), ()> {
305 public_api::set_callback(&self.0, name, Box::new(handler))
306 }
307
308 pub fn get_global_property(&self, global: &str, property: &str) -> Option<Value> {
309 public_api::get_global(&self.0, global, property)
310 }
311
312 pub fn set_global_property(
313 &self,
314 global: &str,
315 property: &str,
316 value: Value,
317 ) -> Result<(), crate::api::SetPropertyError> {
318 public_api::set_global(&self.0, global, property, value)
319 }
320
321 pub fn set_global_callback(
322 &self,
323 global: &str,
324 name: &str,
325 handler: impl Fn(&[Value]) -> Value + 'static,
326 ) -> Result<(), ()> {
327 public_api::set_global_callback(&self.0, global, name, Box::new(handler))
328 }
329
330 pub fn invoke_global(&self, global: &str, name: &str, args: &[Value]) -> Option<Value> {
331 public_api::invoke_global(&self.0, global, name, args)
332 }
333
334 pub fn window_adapter_ref(
338 &self,
339 ) -> Result<&i_slint_core::window::WindowAdapterRc, i_slint_core::api::PlatformError> {
340 self.0.try_window_adapter()?;
341 Ok(self.0.window_adapter.get().expect("window_adapter just initialized above"))
342 }
343
344 pub fn top_level_type(&self) -> i_slint_compiler::llr::TopLevelComponentType {
347 let unit = &self.0.root_sub_component.compilation_unit;
348 match self.0.public_component_index {
349 Some(idx) => unit.public_components[idx].top_level_type,
350 None => i_slint_compiler::llr::TopLevelComponentType::Window,
351 }
352 }
353
354 pub fn definition(&self) -> ComponentDefinitionInner {
356 let public_index = self.0.public_component_index.unwrap_or(0.into());
357 ComponentDefinitionInner {
358 compilation_unit: self.0.root_sub_component.compilation_unit.clone(),
359 public_index,
360 type_loaders: self.0.type_loaders.clone(),
361 resources: self.0.globals.resources.clone(),
362 }
363 }
364}
365
366#[cfg(feature = "std")]
367pub fn build_from_document(
370 document: &i_slint_compiler::object_tree::Document,
371 compiler_config: &i_slint_compiler::CompilerConfiguration,
372 mut type_loaders: TypeLoaders,
373 font_files: FontFiles,
374 animation_mode: AnimationMode,
375) -> Vec<ComponentDefinitionInner> {
376 let resources = Rc::new(Resources {
377 font_files,
378 #[cfg(feature = "internal-mcu-interpreter")]
379 pre_rendered: crate::static_resources::PreRendered::from_document(document),
380 });
381 let mut unit =
382 i_slint_compiler::llr::lower_to_item_tree::lower_to_item_tree(document, compiler_config);
383 if matches!(animation_mode, AnimationMode::Static) {
384 make_static(&mut unit);
385 }
386 let unit = Rc::new(unit);
387 type_loaders.originals = Rc::new(document.exported_roots().collect());
390 unit.public_components
391 .keys()
392 .map(|public_index| ComponentDefinitionInner {
393 compilation_unit: unit.clone(),
394 public_index,
395 type_loaders: type_loaders.clone(),
396 resources: resources.clone(),
397 })
398 .collect()
399}
400
401#[cfg(feature = "std")]
402fn make_static(compilation_unit: &mut CompilationUnit) {
403 fn make_expression_static(expression: &mut Expression) {
404 let replacement = match expression {
405 Expression::BuiltinFunctionCall { function, .. } => match function {
406 BuiltinFunction::AnimationTick => Some(Expression::NumberLiteral(0.)),
407 BuiltinFunction::RestartTimer | BuiltinFunction::UpdateTimers => {
408 Some(Expression::CodeBlock(Vec::new()))
409 }
410 _ => None,
411 },
412 _ => None,
413 };
414 if let Some(replacement) = replacement {
415 *expression = replacement;
416 }
417 }
418
419 compilation_unit.for_each_expression(&mut |expression, _| {
420 expression.borrow_mut().visit_recursive_mut(&mut make_expression_static);
421 });
422 for sub_component in &compilation_unit.sub_components {
423 for popup in &sub_component.popup_windows {
424 popup.position.borrow_mut().visit_recursive_mut(&mut make_expression_static);
425 }
426 }
427 for sub_component in &mut compilation_unit.sub_components {
428 sub_component.timers.clear();
429 sub_component.animations.clear();
430 for (_, binding) in &mut sub_component.property_init {
431 binding.animation = None;
432 }
433 }
434}
435
436#[cfg(feature = "std")]
440#[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), allow(unused_variables))]
441async fn load_font_files(
442 type_loader: &i_slint_compiler::typeloader::TypeLoader,
443 config: &i_slint_compiler::CompilerConfiguration,
444 resource_loader: Option<&ResourceLoader>,
445 diag: &mut i_slint_compiler::diagnostics::BuildDiagnostics,
446) -> FontFiles {
447 let mut imports = std::collections::BTreeMap::new();
448 for doc in type_loader.all_documents() {
449 for (path, token) in &doc.custom_fonts {
450 imports.entry(path.clone()).or_insert_with(|| token.clone());
451 }
452 }
453 let mut loads = Vec::new();
455 for (path, token) in imports {
456 let load = match resource_loader {
457 Some(loader) => loader(path.clone()),
458 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
459 None => Box::pin(fetch(&mapped_url(&path, config).await)),
460 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
461 None => return Default::default(),
462 };
463 loads.push((path, token, load));
464 }
465 let mut files = HashMap::new();
466 for (path, token, load) in loads {
467 match load.await {
468 Ok(data) => {
469 files.insert(path.to_string(), alloc::sync::Arc::new(data));
470 }
471 Err(e) => diag.push_warning(format!("Cannot load the font: {e}"), &token),
472 }
473 }
474 files
475}
476
477#[cfg(all(feature = "std", target_arch = "wasm32", target_os = "unknown"))]
478async fn mapped_url(path: &SourcePath, config: &i_slint_compiler::CompilerConfiguration) -> String {
479 if let (Some(mapper), Some(url)) = (&config.resource_url_mapper, path.to_url())
480 && let Some(mapped) = mapper(&url).await
481 {
482 return mapped.to_string();
483 }
484 path.to_string()
485}
486
487#[cfg(all(feature = "std", target_arch = "wasm32", target_os = "unknown"))]
489fn fetch(url: &str) -> impl Future<Output = std::io::Result<Vec<u8>>> + 'static {
490 use wasm_bindgen::JsCast;
491 use wasm_bindgen_futures::JsFuture;
492 let request = web_sys::window().map(|window| JsFuture::from(window.fetch_with_str(url)));
493 async move {
494 let error = |e: wasm_bindgen::JsValue| std::io::Error::other(format!("{e:?}"));
495 let response: web_sys::Response = request
496 .ok_or_else(|| std::io::Error::other("no browser window"))?
497 .await
498 .map_err(error)?
499 .dyn_into()
500 .map_err(error)?;
501 if !response.ok() {
502 return Err(std::io::Error::other(format!(
503 "{} {}",
504 response.status(),
505 response.status_text()
506 )));
507 }
508 let buffer =
509 JsFuture::from(response.array_buffer().map_err(error)?).await.map_err(error)?;
510 Ok(js_sys::Uint8Array::new(&buffer).to_vec())
511 }
512}
513
514#[cfg(feature = "std")]
515pub struct BuildResult {
520 pub diagnostics: Vec<i_slint_compiler::diagnostics::Diagnostic>,
521 pub components: HashMap<String, ComponentDefinitionInner>,
522 #[cfg(feature = "internal")]
523 pub watch_paths: Vec<SourcePath>,
524 #[cfg(feature = "internal")]
525 pub structs_and_enums: Vec<LangType>,
526}
527
528#[cfg(feature = "std")]
529pub async fn build_from_source(
531 source_code: String,
532 path: SourcePath,
533 mut config: i_slint_compiler::CompilerConfiguration,
534 animation_mode: AnimationMode,
535 resource_loader: Option<ResourceLoader>,
536) -> BuildResult {
537 if config.style.as_deref() == Some("native") {
539 #[cfg(target_arch = "wasm32")]
541 let target = web_sys::window()
542 .and_then(|window| window.navigator().platform().ok())
543 .map_or("wasm", |platform| {
544 let platform = platform.to_ascii_lowercase();
545 if platform.contains("mac")
546 || platform.contains("iphone")
547 || platform.contains("ipad")
548 {
549 "apple"
550 } else if platform.contains("android") {
551 "android"
552 } else if platform.contains("win") {
553 "windows"
554 } else if platform.contains("linux") {
555 "linux"
556 } else {
557 "wasm"
558 }
559 });
560 #[cfg(not(target_arch = "wasm32"))]
561 let target = "";
562 config.style = Some(
563 i_slint_common::get_native_style(i_slint_backend_selector::HAS_NATIVE_STYLE, target)
564 .to_string(),
565 );
566 }
567 if std::env::var_os("SLINT_INLINING").is_none() {
571 config.inline_all_elements = false;
572 }
573 config.debug_info = true;
576 let diag = i_slint_compiler::diagnostics::BuildDiagnostics::default();
577 let (mut diag, loader, raw_loader) = i_slint_compiler::load_root_file_with_raw_type_loader(
578 &path,
579 source_code,
580 diag,
581 config.clone(),
582 )
583 .await;
584 #[cfg(feature = "internal")]
585 let watch_paths = loader.all_files_to_watch().into_iter().collect();
586 let error_result = |diagnostics| BuildResult {
587 diagnostics,
588 components: Default::default(),
589 #[cfg(feature = "internal")]
590 watch_paths: Vec::new(),
591 #[cfg(feature = "internal")]
592 structs_and_enums: Vec::new(),
593 };
594 if diag.has_errors() {
595 return BuildResult {
596 #[cfg(feature = "internal")]
597 watch_paths,
598 ..error_result(diag.into_iter().collect())
599 };
600 }
601 let type_loader = Rc::new(loader);
602 let type_loaders = TypeLoaders {
603 type_loader: Some(type_loader.clone()),
604 raw_type_loader: raw_loader.map(Rc::new),
605 originals: Default::default(),
606 };
607 let doc = match type_loader.get_document(&path) {
608 Some(doc) => doc,
609 None => {
610 return BuildResult {
611 #[cfg(feature = "internal")]
612 watch_paths,
613 ..error_result(diag.into_iter().collect())
614 };
615 }
616 };
617 let font_files =
618 load_font_files(&type_loader, &config, resource_loader.as_ref(), &mut diag).await;
619 let mut components = HashMap::new();
620 for def in build_from_document(doc, &config, type_loaders, font_files, animation_mode) {
621 components.insert(def.name().to_string(), def);
622 }
623 if components.is_empty()
624 && !matches!(config.components_to_generate, ComponentSelection::AllExported)
625 {
626 diag.push_error_with_span("No component found".into(), Default::default());
627 }
628 #[cfg(feature = "internal")]
629 let structs_and_enums = doc.used_types.borrow().structs_and_enums.clone();
630 BuildResult {
631 diagnostics: diag.into_iter().collect(),
632 components,
633 #[cfg(feature = "internal")]
634 watch_paths,
635 #[cfg(feature = "internal")]
636 structs_and_enums,
637 }
638}