Skip to main content

qtbridge_gen/qt_resource/
include_bytes.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use quote::quote;
5use syn::spanned::Spanned;
6
7use qtbridge_build_utils::file_system_utils::{find_all_files, get_relative_path, normalize_dir_separators, parent_dir};
8
9struct Input {
10    file: String,
11    prefix: Option<String>,
12}
13
14impl syn::parse::Parse for Input {
15    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
16        let file: syn::LitStr = input.parse()?;
17        let comma: Option<syn::Token![,]> = input.parse()?;
18        let mut prefix = None;
19        if comma.is_some() {
20            prefix = Some(input.parse::<syn::LitStr>()?);
21        }
22
23        Ok(Self {
24            file: file.value(),
25            prefix: prefix.map(|p| p.value()),
26        })
27    }
28}
29pub fn include_bytes_qml(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
30    include_bytes_qml_impl(input).unwrap_or_else(syn::Error::into_compile_error)
31}
32
33pub fn include_bytes_qml_impl(
34    input: proc_macro2::TokenStream,
35) -> syn::Result<proc_macro2::TokenStream> {
36    let input_span = input.span();
37
38    let Input { file, prefix } = syn::parse2(input)?;
39    let prefix = prefix.unwrap_or_default();
40
41    // `local_file()` gives the on-disk path of the invoking source file, just
42    // like the built-in `include_bytes!`. It requires a toolchain that exposes
43    // the source location to procedural macros; if it doesn't, emit a clear
44    // diagnostic instead of panicking.
45    let Some(span_file) = input_span.local_file() else {
46        return Err(syn::Error::new(
47            input_span,
48            "include_bytes_qml! could not determine the invoking source file path. \
49             This requires a compiler/toolchain that exposes the on-disk source \
50             location to procedural macros.",
51        ));
52    };
53
54    // `local_file()` returns the call-site path relative to rustc's working
55    // directory. As a proc-macro we run inside rustc, so `current_dir()` is
56    // exactly that directory and is the correct anchor to join against.
57    let span_file_path = if span_file.is_absolute() {
58        span_file
59    } else {
60        match std::env::current_dir() {
61            Ok(dir) => dir.join(&span_file),
62            Err(err) => {
63                return Err(syn::Error::new(
64                    input_span,
65                    format!(
66                        "include_bytes_qml! failed to resolve the current directory.\nError: {err}"
67                    ),
68                ));
69            }
70        }
71    };
72
73    let span_file_dir = match parent_dir(&span_file_path) {
74        Ok(span_file_dir) => span_file_dir,
75        Err(err) => return Err(syn::Error::new(input_span, err)),
76    };
77
78    let include_path = span_file_dir.join(&file);
79
80    let files = if include_path.is_file() {
81        vec![(file.clone(), include_path)]
82    } else if include_path.is_dir() {
83        let files = find_all_files(&include_path, true).map_err(|err| {
84            syn::Error::new(
85                input_span,
86                format!(
87                    "Failed to read directory '{}'.\n{err}",
88                    include_path.display()
89                ),
90            )
91        })?;
92        files
93            .into_iter()
94            .map(|absolute_path| {
95                let relative_path = normalize_dir_separators(&get_relative_path(&absolute_path, &include_path)
96                    .expect("find_all_files should only return files under include_path"));
97                let resource_path =
98                    format!("{}/{}", file.trim_end_matches('/'), relative_path.display());
99                (resource_path, absolute_path)
100            })
101            .collect()
102    } else {
103        return Err(syn::Error::new(
104            input_span,
105            format!("Path '{}' does not exist.", include_path.display()),
106        ));
107    };
108    let mut output = proc_macro2::TokenStream::new();
109    for (resource_path, absolute_path) in files {
110        let raw_data = std::fs::read(&absolute_path).map_err(|err| {
111            syn::Error::new(
112                input_span,
113                format!(
114                    "Failed to read file '{}'.\nError: {err}",
115                    absolute_path.display()
116                ),
117            )
118        })?;
119        let mut folder_chain: Vec<&str> = prefix.split('/').filter(|s| !s.is_empty()).collect();
120        folder_chain.extend(resource_path.split('/').filter(|s| !s.is_empty()));
121        let file = build_qt_resource(&raw_data, &folder_chain);
122        output.extend(quote! {
123            // tell the compiler that a rebuild is required when #file changes.
124            // include_bytes! is a build-in macro that has this side effect.
125            let _ = include_bytes!(#resource_path);
126            qtbridge::qresource::register_bytes(&[
127                #(#file),*
128            ]);
129        });
130    }
131    Ok(output)
132}
133
134fn build_qt_resource(raw_data: &[u8], folder_chain: &[&str]) -> Vec<u8> {
135    let overall_flags: usize = 0;
136    let mut data = Vec::<u8>::new();
137    let mut names_offsets = Vec::<usize>::new();
138
139    let qt_hash = |key: &str| -> u32 {
140        let mut h: u32 = 0;
141        for c in key.chars() {
142            h = (h << 4).wrapping_add(c as u32);
143            h ^= (h & 0xf0000000) >> 23;
144        }
145        h & 0x0fffffff
146    };
147
148    let write_u32_be = |data: &mut Vec<u8>, start: usize, value: u32| {
149        data[start..start + 4].copy_from_slice(&value.to_be_bytes());
150    };
151
152    let append_u64_be = |data: &mut Vec<u8>, value: u64| {
153        data.extend_from_slice(&value.to_be_bytes());
154    };
155
156    let append_u32_be = |data: &mut Vec<u8>, value: u32| {
157        data.extend_from_slice(&value.to_be_bytes());
158    };
159
160    let append_u16_be = |data: &mut Vec<u8>, value: u16| {
161        data.extend_from_slice(&value.to_be_bytes());
162    };
163
164    let append_utf16_be = |data: &mut Vec<u8>, s: &str| {
165        for unit in s.encode_utf16() {
166            data.extend_from_slice(&unit.to_be_bytes());
167        }
168    };
169
170    let append_folder_entry = |data: &mut Vec<u8>,
171                               name_offset: u32,
172                               flags: u16,
173                               children_size: u32,
174                               children_offset: u32,
175                               date_modified: u64| {
176        append_u32_be(data, name_offset);
177        append_u16_be(data, flags);
178        append_u32_be(data, children_size);
179        append_u32_be(data, children_offset);
180        append_u64_be(data, date_modified);
181    };
182
183    let append_file_entry = |data: &mut Vec<u8>,
184                             name_offset: u32,
185                             flags: u16,
186                             territory: u16,
187                             language: u16,
188                             data_offset: u32,
189                             date_modified: u64| {
190        append_u32_be(data, name_offset);
191        append_u16_be(data, flags);
192        append_u16_be(data, territory);
193        append_u16_be(data, language);
194        append_u32_be(data, data_offset);
195        append_u64_be(data, date_modified);
196    };
197
198    // see qtbase/src/tools/rcc
199    // RCCResourceLibrary::output
200    data.extend_from_slice(b"qres");
201    append_u32_be(&mut data, 3); // version
202    data.extend(std::iter::repeat_n(0, 16)); // reserve space
203
204    // see qtbase/src/tools/rcc
205    // RCCFileInfo::writeDataBlobs
206    let data_offset = data.len();
207    append_u32_be(&mut data, raw_data.len() as u32);
208    data.extend_from_slice(raw_data);
209
210    // see qtbase/src/tools/rcc
211    // RCCResourceLibrary::writeDataNames
212    let names_offset = data.len();
213    for name in folder_chain {
214        names_offsets.push(data.len() - names_offset);
215        append_u16_be(&mut data, name.len() as u16);
216        append_u32_be(&mut data, qt_hash(name));
217        append_utf16_be(&mut data, name);
218    }
219
220    // see qtbase/src/tools/rcc
221    // RCCResourceLibrary::writeDataStructure
222    let tree_offset = data.len();
223    // root
224    append_folder_entry(&mut data, 0, 2, 1, 1, 0);
225    // folders
226    for (i, n_off) in (2..).zip(names_offsets[..names_offsets.len().saturating_sub(1)].iter()) {
227        append_folder_entry(&mut data, *n_off as u32, 2, 1, i, 0);
228    }
229
230    append_file_entry(&mut data, *names_offsets.last().unwrap() as u32, 0, 0, 1, 0, 0);
231
232    // see qtbase/src/tools/rcc
233    // RCCResourceLibrary::writeInitializer
234    write_u32_be(&mut data, 8, tree_offset as u32);
235    write_u32_be(&mut data, 12, data_offset as u32);
236    write_u32_be(&mut data, 16, names_offset as u32);
237    write_u32_be(&mut data, 20, overall_flags as u32);
238
239    data
240}