Skip to main content

slint_build/
lib.rs

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/*!
5This crate serves as a companion crate of the slint crate.
6It is meant to allow you to compile the `.slint` files from your `build.rs` script.
7
8The main entry point of this crate is the [`compile()`] function
9
10The generated code must be included in your crate by using the `slint::include_modules!()` macro.
11
12## Project File
13
14If the path is a directory, Slint loads the project file (`slint-project.json`) inside that directory.
15The project file provides settings not specified through [`CompilerConfiguration`].
16It must contain a `main` entry, which specifies the `.slint` file the compiler loads.
17Passing a `.slint` file compiles it without loading a project file.
18
19## Example
20
21In your Cargo.toml:
22
23```toml
24[package]
25...
26build = "build.rs"
27
28[dependencies]
29slint = "1.16.0"
30...
31
32[build-dependencies]
33slint-build = "1.16.0"
34```
35
36In the `build.rs` file:
37
38```ignore
39fn main() {
40    slint_build::compile("ui/hello.slint").unwrap();
41}
42```
43
44Then in your main file
45
46```ignore
47slint::include_modules!();
48fn main() {
49    HelloWorld::new().run();
50}
51```
52*/
53#![cfg_attr(
54    feature = "document-features",
55    doc = concat!("## Feature flags\n\n", document_features::document_features!())
56)]
57#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
58#![warn(missing_docs)]
59
60#[cfg(not(feature = "compat-1-18"))]
61compile_error!(
62    "The feature `compat-1-18` must be enabled to ensure \
63    forward compatibility with future version of this crate"
64);
65
66use std::collections::HashMap;
67use std::env;
68use std::io::{BufWriter, Write};
69use std::path::{Path, PathBuf};
70
71use i_slint_compiler::diagnostics::BuildDiagnostics;
72#[cfg(test)]
73use i_slint_compiler::project_file::FILE_NAME as PROJECT_FILE_NAME;
74use i_slint_compiler::project_file::{self, ProjectFile};
75use i_slint_compiler::source_path::SourcePath;
76
77/// Argument of [`CompilerConfiguration::with_default_translation_context()`]
78///
79pub use i_slint_compiler::DefaultTranslationContext;
80
81/// The structure for configuring aspects of the compilation of `.slint` markup files to Rust.
82#[derive(Clone, Default)]
83pub struct CompilerConfiguration {
84    overrides: project_file::Overrides,
85}
86
87/// How should the Slint compiler embed images and fonts
88///
89/// Parameter of [`CompilerConfiguration::embed_resources()`]
90#[derive(Clone, PartialEq)]
91pub enum EmbedResourcesKind {
92    /// Resources are loaded from their absolute path at run-time.
93    ///
94    /// Only useful for debugging, since the files must still be present at the same path on the
95    /// machine running the application.
96    AsAbsolutePath,
97    /// The files referenced from .slint files are embedded in the binary as-is (for example
98    /// a PNG stays compressed), and decoded at run-time.
99    EmbedFiles,
100    #[cfg(feature = "renderer-software")]
101    /// Images and fonts are pre-processed at compile time and embedded as uncompressed pixel
102    /// data, ready to be drawn by the software renderer without any decoding at run-time.
103    ///
104    /// Useful for MCUs with no file system and little RAM.
105    /// Only the Slint software renderer can use these resources; Skia and FemtoVG can't.
106    ///
107    /// Animated images keep only their first frame.
108    EmbedForSoftwareRenderer,
109}
110
111impl CompilerConfiguration {
112    /// Creates a new default configuration.
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    /// Create a new configuration that includes sets the include paths used for looking up
118    /// `.slint` imports to the specified vector of paths.
119    ///
120    /// These paths come before the include paths of the project file.
121    #[must_use]
122    pub fn with_include_paths(mut self, include_paths: Vec<std::path::PathBuf>) -> Self {
123        self.overrides.project.include_paths = Some(include_paths);
124        self
125    }
126
127    /// Create a new configuration that sets the library paths used for looking up
128    /// `@library` imports to the specified map of paths.
129    ///
130    /// Each library path can either be a path to a `.slint` file or a directory.
131    /// If it's a file, the library is imported by its name prefixed by `@` (e.g.
132    /// `@example`). The specified file is the only entry-point for the library
133    /// and other files from the library won't be accessible from the outside.
134    /// If it's a directory, a specific file in that directory must be specified
135    /// when importing the library (e.g. `@example/widgets.slint`). This allows
136    /// exposing multiple entry-points for a single library.
137    ///
138    /// Compile `ui/main.slint` and specify an "example" library path:
139    /// ```rust,no_run
140    /// let manifest_dir = std::path::PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap());
141    /// let library_paths = std::collections::HashMap::from([(
142    ///     "example".to_string(),
143    ///     manifest_dir.join("third_party/example/ui/lib.slint"),
144    /// )]);
145    /// let config = slint_build::CompilerConfiguration::new().with_library_paths(library_paths);
146    /// slint_build::compile_with_config("ui/main.slint", config).unwrap();
147    /// ```
148    ///
149    /// Import the "example" library in `ui/main.slint`:
150    /// ```slint,ignore
151    /// import { Example } from "@example";
152    /// ```
153    ///
154    /// A library here replaces the project file's library of the same name.
155    /// The project file's other libraries stay available.
156    #[must_use]
157    pub fn with_library_paths(
158        mut self,
159        library_paths: HashMap<String, std::path::PathBuf>,
160    ) -> Self {
161        self.overrides.project.library_paths = Some(library_paths);
162        self
163    }
164
165    /// Create a new configuration that selects the style to be used for widgets.
166    ///
167    #[must_use]
168    pub fn with_style(mut self, style: String) -> Self {
169        self.overrides.style = Some(style);
170        self
171    }
172
173    /// Selects how the resources such as images and font are processed.
174    ///
175    /// See [`EmbedResourcesKind`]
176    #[must_use]
177    pub fn embed_resources(mut self, kind: EmbedResourcesKind) -> Self {
178        self.overrides.embed_resources = Some(match kind {
179            EmbedResourcesKind::AsAbsolutePath => {
180                i_slint_compiler::EmbedResourcesKind::OnlyBuiltinResources
181            }
182            EmbedResourcesKind::EmbedFiles => {
183                i_slint_compiler::EmbedResourcesKind::EmbedAllResources
184            }
185            #[cfg(feature = "renderer-software")]
186            EmbedResourcesKind::EmbedForSoftwareRenderer => {
187                i_slint_compiler::EmbedResourcesKind::EmbedTextures
188            }
189        });
190        self
191    }
192
193    /// Sets the scale factor to be applied to all `px` to `phx` conversions
194    /// as constant value. This is only intended for MCU environments. Use
195    /// in combination with [`Self::embed_resources`] to pre-scale images and glyphs
196    /// accordingly.
197    ///
198    /// If this is set, changing the scale factor at runtime will not have any effect.
199    #[must_use]
200    pub fn with_scale_factor(mut self, factor: f32) -> Self {
201        self.overrides.const_scale_factor = Some(factor);
202        self
203    }
204
205    /// Configures the compiler to bundle translations when compiling Slint code.
206    ///
207    /// It expects the path to be the root directory of the translation files.
208    ///
209    /// If given a relative path, it will be resolved relative to `$CARGO_MANIFEST_DIR`.
210    ///
211    /// The translation files should be in the gettext `.po` format and follow this pattern:
212    /// `<path>/<lang>/LC_MESSAGES/<crate>.po`
213    #[must_use]
214    pub fn with_bundled_translations(
215        mut self,
216        path: impl Into<std::path::PathBuf>,
217    ) -> CompilerConfiguration {
218        self.overrides.bundled_translations_path = Some(path.into());
219        self
220    }
221
222    /// Unless explicitly specified with the `@tr("context" => ...)`, the default translation context is the component name.
223    /// Use this option with [`DefaultTranslationContext::None`] to disable the default translation context.
224    ///
225    /// The translation file must also not have context
226    /// (`--no-default-translation-context` argument of `slint-tr-extractor`)
227    #[must_use]
228    pub fn with_default_translation_context(
229        mut self,
230        default_translation_context: DefaultTranslationContext,
231    ) -> Self {
232        self.overrides.default_translation_context = Some(default_translation_context);
233        self
234    }
235
236    /// Configures the compiler to emit additional debug info when compiling Slint code.
237    ///
238    /// This is the equivalent to setting `SLINT_EMIT_DEBUG_INFO=1` and using the `slint!()` macro
239    /// and is primarily used by `i-slint-backend-testing`.
240    #[doc(hidden)]
241    #[must_use]
242    pub fn with_debug_info(mut self, enable: bool) -> Self {
243        self.overrides.debug_info = Some(enable);
244        self
245    }
246
247    /// Configures the compiler to treat the Slint as part of a library.
248    ///
249    /// Use this when the components and types of the Slint code need
250    /// to be accessible from other modules.
251    ///
252    /// **Note**: This feature is experimental and may change or be removed in the future.
253    #[cfg(feature = "experimental-module-builds")]
254    #[must_use]
255    pub fn as_library(mut self, library_name: &str) -> Self {
256        self.overrides.library_name = Some(library_name.to_string());
257        self
258    }
259
260    /// Specifies the Rust module path containing the library's generated exports, such as `backend::ui`.
261    ///
262    /// Use this with [`Self::as_library()`] so consuming crates can locate those exports.
263    /// Place `slint::include_modules!()` inside the corresponding Rust module.
264    /// The path must be relative to the library crate's root, without `crate`, `self`, or `super` prefixes.
265    /// Invalid paths are reported as compilation errors.
266    ///
267    /// **Note**: This feature is experimental and may change or be removed in the future.
268    #[cfg(feature = "experimental-module-builds")]
269    #[must_use]
270    pub fn rust_module(mut self, rust_module: &str) -> Self {
271        self.overrides.rust_module = Some(rust_module.to_string());
272        self
273    }
274    /// Configures the compiler to use Signed Distance Field (SDF) encoding for fonts.
275    ///
276    /// This flag only takes effect when `embed_resources` is set to [`EmbedResourcesKind::EmbedForSoftwareRenderer`],
277    /// and requires the `sdf-fonts` cargo feature to be enabled.
278    ///
279    /// [SDF](https://en.wikipedia.org/wiki/Signed_distance_function) reduces the binary size by
280    /// using an alternative representation for fonts, trading off some rendering quality
281    /// for a smaller binary footprint.
282    /// Rendering is slower and may result in slightly inferior visual output.
283    /// Use this on systems with limited flash memory.
284    #[cfg(feature = "sdf-fonts")]
285    #[must_use]
286    pub fn with_sdf_fonts(mut self, enable: bool) -> Self {
287        self.overrides.use_sdf_fonts = Some(enable);
288        self
289    }
290
291    /// Converts any relative include_paths or library_paths to absolute paths relative to the manifest_dir.
292    #[must_use]
293    fn with_absolute_paths(mut self, manifest_dir: &std::path::Path) -> Self {
294        let to_absolute_path = |path: &mut std::path::PathBuf| {
295            *path = project_file::resolve_relative_path(manifest_dir, std::mem::take(path));
296        };
297
298        for path in
299            self.overrides.project.library_paths.iter_mut().flat_map(|paths| paths.values_mut())
300        {
301            to_absolute_path(path);
302        }
303
304        for path in self.overrides.project.include_paths.iter_mut().flatten() {
305            to_absolute_path(path);
306        }
307
308        self
309    }
310
311    /// Applies `project_file`, then the settings set through this API.
312    fn resolve(
313        self,
314        project_file: Option<&ProjectFile>,
315    ) -> i_slint_compiler::CompilerConfiguration {
316        let mut config = i_slint_compiler::CompilerConfiguration::new(
317            i_slint_compiler::generator::OutputFormat::Rust,
318        );
319        self.overrides.apply(project_file, &mut config);
320        config
321    }
322
323    fn resolve_for_cargo(
324        self,
325        project_file: Option<&ProjectFile>,
326        manifest_dir: &Path,
327    ) -> i_slint_compiler::CompilerConfiguration {
328        let mut config = self.with_absolute_paths(manifest_dir).resolve(project_file);
329        if let Some(path) = config.bundled_translations_path.as_mut()
330            && path.is_relative()
331        {
332            *path = manifest_dir.join(&path);
333        }
334        config
335    }
336
337    #[cfg(test)]
338    fn resolve_project_file(
339        self,
340        project_directory: &Path,
341    ) -> Result<(i_slint_compiler::CompilerConfiguration, Option<ProjectFile>), String> {
342        let (_, project_file) = project_file::resolve_input(project_directory)?;
343        Ok((self.resolve(project_file.as_ref()), project_file))
344    }
345}
346
347/// Error returned by the `compile` function
348#[derive(derive_more::Error, derive_more::Display, Debug)]
349#[non_exhaustive]
350pub enum CompileError {
351    /// Cannot read environment variable CARGO_MANIFEST_DIR or OUT_DIR. The build script need to be run via cargo.
352    #[display(
353        "Cannot read environment variable CARGO_MANIFEST_DIR or OUT_DIR. The build script need to be run via cargo."
354    )]
355    NotRunViaCargo,
356    /// Parse error. The error are printed in the stderr, and also are in the vector
357    #[display("{_0:?}")]
358    CompileError(#[error(not(source))] Vec<String>),
359    /// Cannot write the generated file
360    #[display("Cannot write the generated file: {_0}")]
361    SaveError(std::io::Error),
362}
363
364#[cfg(test)]
365fn project_file_path_in(manifest_dir: impl AsRef<Path>) -> PathBuf {
366    manifest_dir.as_ref().join(PROJECT_FILE_NAME)
367}
368
369/// Compile the `.slint` file and generate rust code for it.
370///
371/// The generated code code will be created in the directory specified by
372/// the `OUT` environment variable as it is expected for build script.
373///
374/// The following line need to be added within your crate in order to include
375/// the generated code.
376/// ```ignore
377/// slint::include_modules!();
378/// ```
379///
380/// The path is relative to the `CARGO_MANIFEST_DIR`.
381///
382/// In case of compilation error, the errors are shown in `stderr`, the error
383/// are also returned in the [`CompileError`] enum. You must `unwrap` the returned
384/// result to make sure that cargo make the compilation fail in case there were
385/// errors when generating the code.
386///
387/// Please check out the documentation of the `slint` crate for more information
388/// about how to use the generated code.
389///
390/// This function can only be called within a build script run by cargo.
391///
392/// If the path is a directory, Slint loads the project file (`slint-project.json`) inside that directory.
393/// It must contain a `main` entry, which specifies the `.slint` file the compiler loads.
394/// A `.slint` file path compiles without loading a project file.
395///
396/// See also [`compile_with_config()`] if you want to specify a configuration.
397pub fn compile(path: impl AsRef<std::path::Path>) -> Result<(), CompileError> {
398    compile_with_config(path, CompilerConfiguration::default())
399}
400
401/// Same as [`compile`], but allow to specify a configuration.
402///
403/// Compile `ui/hello.slint` and select the "material" style:
404/// ```rust,no_run
405/// let config =
406///     slint_build::CompilerConfiguration::new()
407///     .with_style("material".into());
408/// slint_build::compile_with_config("ui/hello.slint", config).unwrap();
409/// ```
410///
411/// The project file provides the settings that `config` does not specify.
412pub fn compile_with_config(
413    path: impl AsRef<std::path::Path>,
414    config: CompilerConfiguration,
415) -> Result<(), CompileError> {
416    let manifest_path = std::path::PathBuf::from(
417        env::var_os("CARGO_MANIFEST_DIR").ok_or(CompileError::NotRunViaCargo)?,
418    );
419    let (input, input_files) = load_input(project_file::resolve_relative_path(
420        &manifest_path,
421        path.as_ref().to_path_buf(),
422    ))?;
423
424    let absolute_rust_output_file_path =
425        Path::new(&env::var_os("OUT_DIR").ok_or(CompileError::NotRunViaCargo)?).join(
426            input
427                .source
428                .as_native_path()
429                .and_then(Path::file_stem)
430                .map(Path::new)
431                .unwrap_or_else(|| Path::new("slint_out"))
432                .with_extension("rs"),
433        );
434
435    let config = config.resolve_for_cargo(input.project_file.as_ref(), &manifest_path);
436
437    #[cfg(feature = "experimental-module-builds")]
438    if let Some(library_name) = config.library_name.clone() {
439        let rust_module = config
440            .rust_module
441            .as_deref()
442            .map(i_slint_compiler::generator::rust::parse_rust_module)
443            .transpose()
444            .map_err(|error| CompileError::CompileError(vec![error.to_string()]))?;
445        println!("cargo::metadata=SLINT_LIBRARY_NAME={}", library_name);
446        println!(
447            "cargo::metadata=SLINT_LIBRARY_PACKAGE={}",
448            std::env::var("CARGO_PKG_NAME").ok().unwrap_or_default()
449        );
450        println!("cargo::metadata=SLINT_LIBRARY_SOURCE={}", input.source);
451        if let Some(rust_module) = rust_module {
452            println!("cargo::metadata=SLINT_LIBRARY_MODULE={}", rust_module);
453        }
454    }
455    // Cargo scans a directory dependency recursively, so this also catches an added language.
456    if let Some(bundle_path) = &config.bundled_translations_path {
457        println!("cargo:rerun-if-changed={}", bundle_path.display());
458    }
459
460    let paths_dependencies =
461        compile_resolved(input, input_files, &absolute_rust_output_file_path, config)?;
462
463    for path_dependency in paths_dependencies {
464        println!("cargo:rerun-if-changed={}", path_dependency.display());
465    }
466
467    println!("cargo:rerun-if-env-changed=SLINT_STYLE");
468    println!("cargo:rerun-if-env-changed=SLINT_FONT_SIZES");
469    println!("cargo:rerun-if-env-changed=SLINT_SCALE_FACTOR");
470    println!("cargo:rerun-if-env-changed=SLINT_ASSET_SECTION");
471    println!("cargo:rerun-if-env-changed=SLINT_EMBED_RESOURCES");
472    println!("cargo:rerun-if-env-changed=SLINT_EMIT_DEBUG_INFO");
473    println!("cargo:rerun-if-env-changed=SLINT_LIVE_PREVIEW");
474    println!("cargo:rerun-if-env-changed=SLINT_BUNDLE_TRANSLATIONS");
475    println!("cargo:rerun-if-env-changed=SLINT_ENABLE_EXPERIMENTAL_FEATURES");
476    println!("cargo:rerun-if-env-changed=SLINT_EDITION");
477
478    println!(
479        "cargo:rustc-env=SLINT_INCLUDE_GENERATED={}",
480        absolute_rust_output_file_path.display()
481    );
482
483    Ok(())
484}
485
486/// Similar to [`compile_with_config`], but meant to be used independently of cargo.
487///
488/// Will compile the input file and write the result in the given output file.
489///
490/// Both input and output paths should be absolute.
491///
492/// Doesn't print any cargo messages.
493///
494/// If the input path is a directory, Slint loads the project file (`slint-project.json`) inside that directory.
495/// The project file provides the settings that `config` does not specify.
496/// It must contain a `main` entry, which specifies the `.slint` file the compiler loads.
497///
498/// Returns a list of all input files that were used to generate the output file. (dependencies)
499pub fn compile_with_output_path(
500    input_slint_file_path: impl AsRef<std::path::Path>,
501    output_rust_file_path: impl AsRef<std::path::Path>,
502    config: CompilerConfiguration,
503) -> Result<Vec<std::path::PathBuf>, CompileError> {
504    let (input, input_files) = load_input(input_slint_file_path.as_ref().to_path_buf())?;
505    let config = config.resolve(input.project_file.as_ref());
506    compile_resolved(input, input_files, output_rust_file_path.as_ref(), config)
507}
508
509/// The root file to compile for `path`, which may be a project directory, its contents,
510/// and the files it was found and read from.
511fn load_input(path: PathBuf) -> Result<(project_file::Input, Vec<PathBuf>), CompileError> {
512    let mut diag = BuildDiagnostics::default();
513    let (input, input_files) = spin_on::spin_on(project_file::load_input(
514        &SourcePath::File(path),
515        None,
516        None,
517        None,
518        &mut diag,
519    ));
520    let input = input.ok_or_else(|| {
521        // The messages name their file already
522        let vec = diag.iter().map(|d| d.message().to_string()).collect();
523        diag.print();
524        CompileError::CompileError(vec)
525    })?;
526    Ok((input, input_files.into_iter().filter_map(SourcePath::into_native_path).collect()))
527}
528
529/// Compiles `input` with `compiler_config`, which has its project file applied.
530/// Returns `input_files` and the other files the output depends on.
531fn compile_resolved(
532    input: project_file::Input,
533    input_files: Vec<PathBuf>,
534    output_rust_file_path: &Path,
535    mut compiler_config: i_slint_compiler::CompilerConfiguration,
536) -> Result<Vec<std::path::PathBuf>, CompileError> {
537    let mut diag = BuildDiagnostics::default();
538    let syntax_node =
539        i_slint_compiler::parser::parse(input.source_code, Some(input.source), &mut diag);
540
541    if diag.has_errors() {
542        let vec = diag.to_string_vec();
543        diag.print();
544        return Err(CompileError::CompileError(vec));
545    }
546
547    compiler_config.translation_domain = std::env::var("CARGO_PKG_NAME").ok();
548
549    // 'spin_on' is ok here because the compiler in single threaded and does not block if there is no blocking future
550    let (doc, mut diag, loader) =
551        spin_on::spin_on(i_slint_compiler::compile_syntax_node(syntax_node, diag, compiler_config));
552    diag.remove_infos();
553
554    if diag.has_errors()
555        || (!diag.is_empty() && std::env::var("SLINT_COMPILER_DENY_WARNINGS").is_ok())
556    {
557        let vec = diag.to_string_vec();
558        diag.print();
559        return Err(CompileError::CompileError(vec));
560    }
561
562    let generated = i_slint_compiler::generator::rust::generate(&doc, &loader.compiler_config)
563        .map_err(|e| CompileError::CompileError(vec![e.to_string()]))?;
564    let mut output_file = BufWriter::new(
565        std::fs::File::create(output_rust_file_path).map_err(CompileError::SaveError)?,
566    );
567
568    let mut dependencies = input_files;
569
570    for x in diag.all_loaded_files.iter().filter_map(|p| p.as_native_path()) {
571        if x.is_absolute() {
572            dependencies.push(x.to_path_buf());
573        }
574    }
575
576    // print warnings
577    diag.diagnostics_as_string().lines().for_each(|w| {
578        if !w.is_empty() {
579            println!("cargo:warning={}", w.strip_prefix("warning: ").unwrap_or(w))
580        }
581    });
582
583    i_slint_compiler::generator::rust_code_formatter::write_formatted(&generated, &mut output_file)
584        .map_err(CompileError::SaveError)?;
585
586    for er in doc.embedded_file_resources.borrow().iter() {
587        if let Some(resource) = er.path.as_ref().and_then(|p| p.as_native_path()) {
588            dependencies.push(resource.to_path_buf());
589        }
590    }
591
592    output_file.flush().map_err(CompileError::SaveError)?;
593
594    Ok(dependencies)
595}
596
597/// This function is for use the application's build script, in order to print any device specific
598/// build flags reported by the backend
599pub fn print_rustc_flags() -> std::io::Result<()> {
600    if let Some(board_config_path) =
601        std::env::var_os("DEP_MCU_BOARD_SUPPORT_BOARD_CONFIG_PATH").map(std::path::PathBuf::from)
602    {
603        let config = std::fs::read_to_string(board_config_path.as_path())?;
604        let toml = config.parse::<toml_edit::DocumentMut>().expect("invalid board config toml");
605
606        for link_arg in
607            toml.get("link_args").and_then(toml_edit::Item::as_array).into_iter().flatten()
608        {
609            if let Some(option) = link_arg.as_str() {
610                println!("cargo:rustc-link-arg={option}");
611            }
612        }
613
614        for link_search_path in
615            toml.get("link_search_path").and_then(toml_edit::Item::as_array).into_iter().flatten()
616        {
617            if let Some(mut path) = link_search_path.as_str().map(std::path::PathBuf::from) {
618                if path.is_relative() {
619                    path = board_config_path.parent().unwrap().join(path);
620                }
621                println!("cargo:rustc-link-search={}", path.to_string_lossy());
622            }
623        }
624        println!("cargo:rerun-if-env-changed=DEP_MCU_BOARD_SUPPORT_MCU_BOARD_CONFIG_PATH");
625        println!("cargo:rerun-if-changed={}", board_config_path.display());
626    }
627
628    Ok(())
629}
630
631#[cfg(test)]
632fn root_path_prefix() -> std::path::PathBuf {
633    #[cfg(windows)]
634    return std::path::PathBuf::from("C:/");
635    #[cfg(not(windows))]
636    return std::path::PathBuf::from("/");
637}
638
639#[cfg(test)]
640fn with_temp_test_dir<R>(test_name: &str, f: impl FnOnce(&Path) -> R) -> R {
641    let stamp =
642        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
643    let test_dir =
644        std::env::temp_dir().join("slint-build-tests").join(format!("{test_name}-{stamp}"));
645    std::fs::create_dir_all(&test_dir).unwrap();
646    let result = f(&test_dir);
647    std::fs::remove_dir_all(test_dir).unwrap();
648    result
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654
655    #[test]
656    fn with_absolute_library_paths_test() {
657        use std::path::PathBuf;
658
659        let library_paths = std::collections::HashMap::from([
660            ("relative".to_string(), PathBuf::from("some/relative/path")),
661            ("absolute".to_string(), root_path_prefix().join("some/absolute/path")),
662        ]);
663        let config = CompilerConfiguration::new().with_library_paths(library_paths);
664
665        let manifest_path = root_path_prefix().join("path/to/manifest");
666        let absolute_config = config.clone().with_absolute_paths(&manifest_path);
667        let library_paths = absolute_config.overrides.project.library_paths.unwrap();
668        let relative = &library_paths["relative"];
669        assert!(relative.is_absolute());
670        assert!(relative.starts_with(&manifest_path));
671
672        assert!(!library_paths["absolute"].starts_with(&manifest_path));
673    }
674
675    #[test]
676    fn with_absolute_include_paths_test() {
677        use std::path::PathBuf;
678
679        let config = CompilerConfiguration::new().with_include_paths(Vec::from([
680            root_path_prefix().join("some/absolute/path"),
681            PathBuf::from("some/relative/path"),
682            PathBuf::from("windows\\style"),
683        ]));
684
685        let manifest_path = root_path_prefix().join("path/to/manifest");
686        let absolute_config = config.clone().with_absolute_paths(&manifest_path);
687        assert_eq!(
688            absolute_config.overrides.project.include_paths.unwrap(),
689            Vec::from([
690                root_path_prefix().join("some/absolute/path"),
691                manifest_path.join("some/relative/path"),
692                manifest_path.join("windows").join("style"),
693            ])
694        )
695    }
696
697    #[cfg(feature = "experimental-module-builds")]
698    #[test]
699    fn invalid_rust_module_is_a_compilation_error() {
700        let directory = tempfile::tempdir().unwrap();
701        let source_path = directory.path().join("main.slint");
702        let output_path = directory.path().join("main.rs");
703        std::fs::write(&source_path, "export component Main inherits Window {}").unwrap();
704
705        let config = CompilerConfiguration::new().as_library("TestLibrary").rust_module("🍰🍔🍕");
706        let error = compile_with_output_path(&source_path, &output_path, config).unwrap_err();
707
708        let CompileError::CompileError(messages) = error else {
709            panic!("Expected a compilation error, got {error:?}");
710        };
711        assert!(
712            messages.iter().any(|message| message.contains("Invalid rust_module")),
713            "{messages:?}"
714        );
715        assert!(!output_path.exists());
716    }
717}
718
719#[test]
720fn project_file_defaults_use_project_file_directory_for_relative_paths() {
721    use std::{collections::HashMap, fs};
722
723    with_temp_test_dir("relative-paths", |test_root| {
724        let project_file = project_file_path_in(test_root);
725        fs::write(
726            &project_file,
727            r#"{
728                "slint-edition": "1.19",
729                "main": "main.slint",
730                "include-paths": ["project-include"],
731                "library-paths": {"widgets": "project-lib.slint"}
732            }"#,
733        )
734        .unwrap();
735
736        let test_root = fs::canonicalize(test_root).unwrap();
737        let (config, project_file) = CompilerConfiguration::new()
738            .with_absolute_paths(&test_root)
739            .resolve_project_file(&test_root)
740            .unwrap();
741
742        assert_eq!(config.include_paths, vec![test_root.join("project-include")]);
743        assert_eq!(
744            config.library_paths,
745            HashMap::from([("widgets".to_string(), test_root.join("project-lib.slint"))])
746        );
747        assert_eq!(
748            project_file.unwrap().source_path().as_native_path().unwrap(),
749            project_file_path_in(&test_root)
750        );
751    });
752}
753
754#[test]
755fn explicit_settings_add_to_the_project_file_paths() {
756    use std::{collections::HashMap, fs, path::PathBuf};
757
758    with_temp_test_dir("override-precedence", |test_root| {
759        let project_file = project_file_path_in(test_root);
760        fs::write(
761            &project_file,
762            r#"{
763                "slint-edition": "1.19",
764                "main": "main.slint",
765                "include-paths": ["project-include"],
766                "library-paths": {"widgets": "project-lib.slint", "icons": "icons.slint"}
767            }"#,
768        )
769        .unwrap();
770
771        let test_root = fs::canonicalize(test_root).unwrap();
772        let (config, _) = CompilerConfiguration::new()
773            .with_include_paths(vec![PathBuf::from("build-include")])
774            .with_library_paths(HashMap::from([(
775                "widgets".to_string(),
776                PathBuf::from("build-lib.slint"),
777            )]))
778            .with_style("build-style".into())
779            .with_absolute_paths(&test_root)
780            .resolve_project_file(&test_root)
781            .unwrap();
782
783        assert_eq!(
784            config.include_paths,
785            vec![test_root.join("build-include"), test_root.join("project-include")]
786        );
787        assert_eq!(
788            config.library_paths,
789            HashMap::from([
790                ("widgets".to_string(), test_root.join("build-lib.slint")),
791                ("icons".to_string(), test_root.join("icons.slint")),
792            ])
793        );
794        assert_eq!(config.style.as_deref(), Some("build-style"));
795    });
796}
797
798#[test]
799fn explicit_build_settings_preserve_empty_values_and_false() {
800    with_temp_test_dir("empty-overrides", |test_root| {
801        let project_path = project_file_path_in(test_root);
802        std::fs::write(
803            &project_path,
804            r#"{"slint-edition":"1.19","include-paths":["include"],"library-paths":{"widgets":"lib"}}"#,
805        )
806        .unwrap();
807        let project = ProjectFile::load(project_path).unwrap();
808        let config = CompilerConfiguration::new()
809            .with_include_paths(vec![])
810            .with_library_paths(HashMap::new())
811            .with_style(String::new())
812            .with_scale_factor(0.)
813            .with_bundled_translations(PathBuf::new())
814            .with_default_translation_context(DefaultTranslationContext::None)
815            .with_debug_info(false)
816            .resolve(Some(&project));
817        let project_data = project.resolved_data();
818        assert_eq!(Some(config.include_paths), project_data.include_paths);
819        assert_eq!(Some(config.library_paths), project_data.library_paths);
820        assert_eq!(config.style.as_deref(), Some(""));
821        assert_eq!(config.const_scale_factor, Some(0.));
822        assert_eq!(config.bundled_translations_path, Some(PathBuf::new()));
823        assert_eq!(config.default_translation_context, DefaultTranslationContext::None);
824        assert!(!config.debug_info);
825    });
826}
827
828#[test]
829fn build_settings_adapt_all_resource_kinds() {
830    use i_slint_compiler::EmbedResourcesKind as InternalKind;
831    for (public_kind, internal_kind) in [
832        (EmbedResourcesKind::AsAbsolutePath, InternalKind::OnlyBuiltinResources),
833        (EmbedResourcesKind::EmbedFiles, InternalKind::EmbedAllResources),
834        #[cfg(feature = "renderer-software")]
835        (EmbedResourcesKind::EmbedForSoftwareRenderer, InternalKind::EmbedTextures),
836    ] {
837        assert_eq!(
838            CompilerConfiguration::new().embed_resources(public_kind).resolve(None).embed_resources,
839            internal_kind
840        );
841    }
842}
843
844#[test]
845fn omitted_build_settings_keep_compiler_defaults() {
846    let config = CompilerConfiguration::new().resolve(None);
847    let defaults = i_slint_compiler::CompilerConfiguration::new(
848        i_slint_compiler::generator::OutputFormat::Rust,
849    );
850    assert_eq!(config.embed_resources, defaults.embed_resources);
851    assert_eq!(config.const_scale_factor, defaults.const_scale_factor);
852    assert_eq!(config.bundled_translations_path, defaults.bundled_translations_path);
853    assert_eq!(config.default_translation_context, defaults.default_translation_context);
854    assert_eq!(config.debug_info, defaults.debug_info);
855    assert_eq!(config.library_name, defaults.library_name);
856    assert_eq!(config.rust_module, defaults.rust_module);
857    #[cfg(feature = "sdf-fonts")]
858    assert_eq!(config.use_sdf_fonts, defaults.use_sdf_fonts);
859}
860
861#[test]
862fn cargo_translation_paths_include_environment_defaults() {
863    let manifest_dir = root_path_prefix().join("cargo-manifest");
864    let defaults = i_slint_compiler::CompilerConfiguration::new(
865        i_slint_compiler::generator::OutputFormat::Rust,
866    );
867    assert_eq!(
868        CompilerConfiguration::new()
869            .resolve_for_cargo(None, &manifest_dir)
870            .bundled_translations_path,
871        defaults.bundled_translations_path.map(|path| manifest_dir.join(path))
872    );
873    for path in [PathBuf::from("translations"), root_path_prefix().join("absolute/translations")] {
874        assert_eq!(
875            CompilerConfiguration::new()
876                .with_bundled_translations(&path)
877                .resolve_for_cargo(None, &manifest_dir)
878                .bundled_translations_path,
879            Some(manifest_dir.join(path))
880        );
881    }
882}
883
884#[cfg(feature = "experimental-module-builds")]
885#[test]
886fn build_module_settings_preserve_empty_values() {
887    for name in ["", "widgets"] {
888        let config = CompilerConfiguration::new().as_library(name).rust_module(name).resolve(None);
889        assert_eq!(config.library_name.as_deref(), Some(name));
890        assert_eq!(config.rust_module.as_deref(), Some(name));
891    }
892}
893
894#[cfg(feature = "sdf-fonts")]
895#[test]
896fn build_sdf_settings_preserve_false() {
897    for enabled in [false, true] {
898        let config = CompilerConfiguration::new().with_sdf_fonts(enabled).resolve(None);
899        assert_eq!(config.use_sdf_fonts, enabled);
900    }
901}
902
903#[test]
904fn compiler_configuration_defaults_without_project_file() {
905    use std::fs;
906
907    with_temp_test_dir("optional-project-file", |test_root| {
908        let (config, project_file) = CompilerConfiguration::new()
909            .resolve_project_file(&test_root.join("main.slint"))
910            .unwrap();
911        assert!(config.style.is_none());
912        assert!(project_file.is_none());
913
914        let project_file = project_file_path_in(test_root);
915        fs::write(
916            &project_file,
917            r#"{"slint-edition": "1.19", "main":"main.slint","include-paths":["include"]}"#,
918        )
919        .unwrap();
920
921        let (config, _) = CompilerConfiguration::new().resolve_project_file(test_root).unwrap();
922        assert_eq!(config.include_paths, vec![test_root.join("include")]);
923    });
924}
925
926#[test]
927fn file_compilation_ignores_project_files() {
928    use std::fs;
929
930    with_temp_test_dir("standalone-slint-file", |test_root| {
931        let ui_directory = test_root.join("ui");
932        fs::create_dir_all(&ui_directory).unwrap();
933        fs::write(project_file_path_in(test_root), "{").unwrap();
934        fs::write(project_file_path_in(&ui_directory), "{").unwrap();
935
936        let input_file = ui_directory.join("main.slint");
937        let output_file = test_root.join("main.rs");
938        fs::write(&input_file, "export component Test inherits Rectangle {}").unwrap();
939
940        let dependencies =
941            compile_with_output_path(&input_file, &output_file, CompilerConfiguration::new())
942                .unwrap();
943        assert!(dependencies.contains(&input_file));
944        for project_file in [project_file_path_in(test_root), project_file_path_in(&ui_directory)] {
945            assert!(!dependencies.contains(&project_file), "{dependencies:#?}");
946        }
947    });
948}
949
950#[test]
951fn project_file_discovery_loads_present_paths() {
952    use std::fs;
953
954    with_temp_test_dir("discovery-present-paths", |test_root| {
955        let project_file = project_file_path_in(test_root);
956
957        fs::create_dir_all(&project_file).unwrap();
958
959        // The message for reading a directory differs per platform, so only pin that
960        // it errors instead of being swallowed like a missing file.
961        assert!(CompilerConfiguration::new().resolve_project_file(test_root).is_err());
962    });
963}
964
965#[test]
966fn missing_main_is_a_compilation_error() {
967    use std::fs;
968
969    with_temp_test_dir("project-file-error", |test_root| {
970        let project_file = project_file_path_in(test_root);
971        fs::write(&project_file, r#"{ "slint-edition": "1.19" }"#).unwrap();
972
973        let error = compile_with_output_path(
974            test_root,
975            test_root.join("main.rs"),
976            CompilerConfiguration::new(),
977        )
978        .unwrap_err();
979
980        let CompileError::CompileError(messages) = error else {
981            panic!("Expected a compilation error, got {error:?}");
982        };
983        assert_eq!(messages, vec![format!("{} has no 'main' to compile", project_file.display())]);
984    });
985}
986
987#[test]
988fn output_path_compilation_tracks_project_file_dependency() {
989    use std::fs;
990
991    with_temp_test_dir("output-deps", |test_root| {
992        let project_file = project_file_path_in(test_root);
993        let input_file = test_root.join("main.slint");
994        let output_file = test_root.join("main.rs");
995
996        fs::write(
997            &project_file,
998            r#"{"slint-edition": "1.19", "main":"main.slint","include-paths":["include"]}"#,
999        )
1000        .unwrap();
1001        fs::write(&input_file, "export component Test inherits Rectangle {}").unwrap();
1002
1003        let config = CompilerConfiguration::new();
1004        let dependencies = compile_with_output_path(test_root, &output_file, config).unwrap();
1005
1006        let project_file = i_slint_compiler::source_path::clean_path(&project_file);
1007        assert!(
1008            dependencies.iter().any(|dependency| dependency == &project_file),
1009            "expected: {:?}\ndeps: {dependencies:#?}",
1010            project_file
1011        );
1012    });
1013}
1014
1015#[test]
1016fn output_path_compilation_does_not_track_missing_project_file() {
1017    use std::fs;
1018
1019    with_temp_test_dir("missing-project-deps", |test_root| {
1020        let project_file = project_file_path_in(test_root);
1021        let input_file = test_root.join("main.slint");
1022        let output_file = test_root.join("main.rs");
1023
1024        fs::write(&input_file, "export component Test inherits Rectangle {}").unwrap();
1025
1026        let config = CompilerConfiguration::new();
1027        let dependencies = compile_with_output_path(&input_file, &output_file, config).unwrap();
1028
1029        let project_file = i_slint_compiler::source_path::clean_path(&project_file);
1030        assert!(
1031            dependencies
1032                .iter()
1033                .all(|dependency| i_slint_compiler::source_path::clean_path(dependency)
1034                    != project_file),
1035            "{dependencies:#?}"
1036        );
1037    });
1038}
1039
1040#[test]
1041fn a_project_directory_compiles_its_main_file() {
1042    use std::fs;
1043
1044    with_temp_test_dir("project-file-input", |test_root| {
1045        let test_root = fs::canonicalize(test_root).unwrap();
1046        let ui_dir = test_root.join("ui");
1047        let shared_dir = test_root.join("shared");
1048        fs::create_dir_all(&ui_dir).unwrap();
1049        fs::create_dir_all(&shared_dir).unwrap();
1050
1051        let project_file = project_file_path_in(&test_root);
1052        fs::write(
1053            &project_file,
1054            r#"{ "slint-edition": "1.19", "main": "ui/main.slint", "include-paths": ["shared"] }"#,
1055        )
1056        .unwrap();
1057        fs::write(
1058            project_file_path_in(&ui_dir),
1059            r#"{ "slint-edition": "1.19", "include-paths": ["nowhere"] }"#,
1060        )
1061        .unwrap();
1062        fs::write(shared_dir.join("shared.slint"), "export component Shared {}").unwrap();
1063        let main = ui_dir.join("main.slint");
1064        fs::write(
1065            &main,
1066            r#"import { Shared } from "shared.slint";
1067               export component Test inherits Rectangle { Shared {} }"#,
1068        )
1069        .unwrap();
1070
1071        let dependencies = compile_with_output_path(
1072            &test_root,
1073            test_root.join("main.rs"),
1074            CompilerConfiguration::new(),
1075        )
1076        .unwrap();
1077
1078        assert!(dependencies.contains(&main), "{dependencies:#?}");
1079        assert!(dependencies.contains(&project_file), "{dependencies:#?}");
1080    });
1081}
1082
1083#[test]
1084fn directory_without_project_file_is_a_compilation_error() {
1085    with_temp_test_dir("missing-project-file", |test_root| {
1086        let error = compile_with_output_path(
1087            test_root,
1088            test_root.join("main.rs"),
1089            CompilerConfiguration::new(),
1090        )
1091        .unwrap_err();
1092        assert!(error.to_string().contains("slint-project.json"), "{error}");
1093    });
1094}
1095
1096#[test]
1097fn project_file_cannot_be_compiled_directly() {
1098    with_temp_test_dir("direct-project-file", |test_root| {
1099        let project_file = project_file_path_in(test_root);
1100        std::fs::write(&project_file, r#"{"slint-edition":"1.19","main":"main.slint"}"#).unwrap();
1101        let error = compile_with_output_path(
1102            &project_file,
1103            test_root.join("main.rs"),
1104            CompilerConfiguration::new(),
1105        )
1106        .unwrap_err();
1107        let CompileError::CompileError(messages) = error else {
1108            panic!("Expected a compilation error, got {error:?}");
1109        };
1110        assert_eq!(
1111            messages,
1112            vec![format!(
1113                "A `{PROJECT_FILE_NAME}` cannot be compiled directly; pass its directory instead ({})",
1114                test_root.display()
1115            )]
1116        );
1117    });
1118}