Repository navigation
Expand file tree
/
Copy pathbuild.rs
More file actions
529 lines (487 loc) · 18.8 KB
/
Copy pathbuild.rs
File metadata and controls
529 lines (487 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use epaint_default_fonts::UBUNTU_LIGHT;
use heck::ToKebabCase;
use lucide_icons::{Icon as LucideIcon, LUCIDE_FONT_BYTES};
use oxifont_subset::{subset_font_with_options, SubsetOptions};
use proc_macro2::{TokenStream, TokenTree};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use winresource::{VersionInfo, WindowsResource};
fn main() {
build_locales();
build_themes();
build_lucide_subset();
build_ui_fallback_subset();
let version = env!("CARGO_PKG_VERSION");
// Embed the icon and richer PE version metadata into the executable.
let mut res = WindowsResource::new();
let numeric_version = pack_version(version);
res.set_icon("src/icons/icon.ico")
// Declaring modern Windows compatibility enables WS_EX_LAYERED child
// windows, which the Windows 11 raised desktop requires.
// Keep the manifest in a file so winresource asks the resource compiler to
// embed it verbatim. `set_manifest` wraps every line in spaces, which
// puts whitespace before the XML declaration and breaks parsers such
// as wingetcreate's Vestris.ResourceLib.
.set_manifest_file("src/app.manifest")
.set("FileVersion", version)
.set("ProductVersion", version)
.set_version_info(VersionInfo::FILEVERSION, numeric_version)
.set_version_info(VersionInfo::PRODUCTVERSION, numeric_version);
res.compile().expect("Failed to compile Windows resources");
println!("cargo:rerun-if-changed=src/app.manifest");
}
fn build_themes() {
let output_dir = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR was not set"));
for name in [
"classic-usage-widget.json",
"compact-fluent-quad.json",
"classic-vertical.json",
"minecraft-codex.json",
] {
let path = Path::new("src/themes").join(name);
println!("cargo:rerun-if-changed={}", path.display());
let source = fs::read(&path)
.unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display()));
let theme: serde_json::Value = serde_json::from_slice(&source)
.unwrap_or_else(|error| panic!("Invalid theme file {}: {error}", path.display()));
let minified = serde_json::to_vec(&theme)
.unwrap_or_else(|error| panic!("Failed to minify {}: {error}", path.display()));
let output = output_dir.join(name);
write_if_changed(&output, &minified)
.unwrap_or_else(|error| panic!("Failed to write {}: {error}", output.display()));
}
}
struct LocaleSource {
path: PathBuf,
order: usize,
code: String,
native_name: String,
locale_patterns: Vec<String>,
update_via_winget: String,
windows_font: Option<(String, String)>,
strings: BTreeMap<String, String>,
translations: BTreeMap<String, String>,
}
fn build_locales() {
let locale_dir = Path::new("src/localization/locales");
let mut paths = fs::read_dir(locale_dir)
.unwrap_or_else(|error| panic!("Failed to read {}: {error}", locale_dir.display()))
.map(|entry| entry.expect("Failed to read locale directory entry").path())
.filter(|path| {
path.extension()
.is_some_and(|extension| extension == "toml")
})
.collect::<Vec<_>>();
paths.sort();
assert!(!paths.is_empty(), "No locale files found");
let mut locales = paths
.iter()
.map(|path| read_locale(path))
.collect::<Vec<_>>();
locales.sort_by_key(|locale| locale.order);
validate_locales(&locales);
let english_index = locales
.iter()
.position(|locale| locale.code.eq_ignore_ascii_case("en"))
.expect("An English locale with code 'en' is required");
let mut generated = String::new();
generated.push_str("// Generated by build.rs from src/localization/locales/*.toml.\n");
generated.push_str(&format!(
"pub(super) const LANGUAGE_COUNT: usize = {};\n",
locales.len()
));
generated.push_str(&format!(
"pub(super) const ENGLISH_INDEX: usize = {english_index};\n"
));
generated.push_str("pub(super) const LANGUAGE_IDS: [LanguageId; LANGUAGE_COUNT] = [");
for index in 0..locales.len() {
generated.push_str(&format!("LanguageId({index}),"));
}
generated.push_str("];\n");
generated.push_str("pub(super) static LOCALES: [Locale; LANGUAGE_COUNT] = [\n");
for locale in &locales {
generated.push_str("Locale {\n");
generated.push_str(&format!("code: {:?},\n", locale.code));
generated.push_str(&format!("native_name: {:?},\n", locale.native_name));
generated.push_str("locale_patterns: &[");
for pattern in &locale.locale_patterns {
generated.push_str(&format!("{pattern:?},"));
}
generated.push_str("],\n");
match &locale.windows_font {
Some((name, file)) => {
generated.push_str(&format!("windows_font: Some(({name:?}, {file:?})),\n"));
}
None => generated.push_str("windows_font: None,\n"),
}
generated.push_str(&format!(
"update_via_winget_label: {:?},\n",
locale.update_via_winget
));
generated.push_str("strings: Strings {\n");
for (field, value) in &locale.strings {
generated.push_str(&format!("{field}: {value:?},\n"));
}
generated.push_str("},\ntranslations: &[");
for (key, value) in &locale.translations {
generated.push_str(&format!("({key:?}, {value:?}),"));
}
generated.push_str("],\n},\n");
}
generated.push_str("];\n");
let output =
PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR was not set")).join("locales.rs");
write_if_changed(&output, generated.as_bytes())
.unwrap_or_else(|error| panic!("Failed to write {}: {error}", output.display()));
println!("cargo:rerun-if-changed={}", locale_dir.display());
}
fn read_locale(path: &Path) -> LocaleSource {
let source = fs::read_to_string(path)
.unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display()));
let source = source.strip_prefix('\u{feff}').unwrap_or(&source);
let value = toml::from_str::<toml::Value>(source)
.unwrap_or_else(|error| panic!("Invalid locale file {}: {error}", path.display()));
let table = value
.as_table()
.unwrap_or_else(|| panic!("Locale {} must contain a TOML table", path.display()));
let allowed = [
"code",
"native_name",
"locale_patterns",
"order",
"update_via_winget",
"windows_font_name",
"windows_font_file",
"strings",
"translations",
];
for key in table.keys() {
assert!(
allowed.contains(&key.as_str()),
"Unknown top-level locale key {key:?} in {}",
path.display()
);
}
let font_name = optional_string(table, "windows_font_name", path);
let font_file = optional_string(table, "windows_font_file", path);
assert_eq!(
font_name.is_some(),
font_file.is_some(),
"{} must define both windows_font_name and windows_font_file",
path.display()
);
let order = required_integer(table, "order", path);
assert!(
order >= 0,
"Locale order cannot be negative in {}",
path.display()
);
LocaleSource {
path: path.to_path_buf(),
order: order as usize,
code: required_string(table, "code", path),
native_name: required_string(table, "native_name", path),
locale_patterns: required_string_array(table, "locale_patterns", path),
update_via_winget: required_string(table, "update_via_winget", path),
windows_font: font_name.zip(font_file),
strings: required_string_table(table, "strings", path),
translations: required_string_table(table, "translations", path),
}
}
fn validate_locales(locales: &[LocaleSource]) {
let english = locales
.iter()
.find(|locale| locale.code.eq_ignore_ascii_case("en"))
.expect("An English locale with code 'en' is required");
let string_keys = english.strings.keys().cloned().collect::<BTreeSet<_>>();
let translation_keys = english
.translations
.keys()
.cloned()
.collect::<BTreeSet<_>>();
let mut codes = BTreeSet::new();
let mut orders = BTreeSet::new();
let mut patterns = BTreeSet::new();
for (expected_order, locale) in locales.iter().enumerate() {
assert_eq!(
locale.order,
expected_order,
"Locale orders must be unique and contiguous from zero; check {}",
locale.path.display()
);
assert!(
orders.insert(locale.order),
"Duplicate locale order {}",
locale.order
);
assert!(
codes.insert(locale.code.to_ascii_lowercase()),
"Duplicate locale code {}",
locale.code
);
assert_eq!(
locale.code.trim(),
locale.code,
"Locale code cannot have surrounding whitespace in {}",
locale.path.display()
);
assert!(!locale.code.is_empty(), "Locale code cannot be empty");
assert!(
!locale.native_name.trim().is_empty(),
"Locale native_name cannot be empty in {}",
locale.path.display()
);
assert!(
!locale.locale_patterns.is_empty(),
"locale_patterns cannot be empty in {}",
locale.path.display()
);
for pattern in &locale.locale_patterns {
assert!(!pattern.is_empty(), "Locale patterns cannot be empty");
assert_eq!(
pattern.trim(),
pattern,
"Locale patterns cannot have surrounding whitespace in {}",
locale.path.display()
);
assert_eq!(
pattern,
&pattern.to_ascii_lowercase(),
"Locale patterns must be lowercase in {}",
locale.path.display()
);
assert!(
patterns.insert(pattern),
"Duplicate locale pattern {pattern:?} in {}",
locale.path.display()
);
}
let normalized_code = locale.code.replace('_', "-").to_ascii_lowercase();
assert!(
locale.locale_patterns.iter().any(|pattern| {
normalized_code == *pattern
|| normalized_code
.strip_prefix(pattern)
.is_some_and(|suffix| suffix.starts_with('-'))
}),
"Locale code {:?} is not recognized by its patterns in {}",
locale.code,
locale.path.display()
);
let locale_string_keys = locale.strings.keys().cloned().collect::<BTreeSet<_>>();
assert_eq!(
locale_string_keys,
string_keys,
"Typed string keys differ from English in {}",
locale.path.display()
);
let locale_translation_keys = locale.translations.keys().cloned().collect::<BTreeSet<_>>();
assert_eq!(
locale_translation_keys,
translation_keys,
"Translation keys differ from English in {}",
locale.path.display()
);
for (key, value) in &locale.translations {
assert!(!value.trim().is_empty(), "Empty translation for {key:?}");
let english_value = &english.translations[key];
assert_eq!(
placeholders(value),
placeholders(english_value),
"Placeholders differ for {key:?} in {}",
locale.path.display()
);
}
for (key, value) in &locale.strings {
assert!(!value.trim().is_empty(), "Empty typed string {key:?}");
let english_value = &english.strings[key];
assert_eq!(
placeholders(value),
placeholders(english_value),
"Placeholders differ for typed string {key:?} in {}",
locale.path.display()
);
}
}
}
fn placeholders(value: &str) -> Vec<&str> {
let mut placeholders = Vec::new();
let mut remainder = value;
while let Some(start) = remainder.find('{') {
let candidate = &remainder[start..];
let Some(end) = candidate.find('}') else {
break;
};
placeholders.push(&candidate[..=end]);
remainder = &candidate[end + 1..];
}
placeholders.sort_unstable();
placeholders
}
fn required_string(table: &toml::Table, key: &str, path: &Path) -> String {
table
.get(key)
.and_then(toml::Value::as_str)
.unwrap_or_else(|| panic!("Missing string {key:?} in {}", path.display()))
.to_owned()
}
fn optional_string(table: &toml::Table, key: &str, path: &Path) -> Option<String> {
table.get(key).map(|value| {
value
.as_str()
.unwrap_or_else(|| panic!("{key:?} must be a string in {}", path.display()))
.to_owned()
})
}
fn required_integer(table: &toml::Table, key: &str, path: &Path) -> i64 {
table
.get(key)
.and_then(toml::Value::as_integer)
.unwrap_or_else(|| panic!("Missing integer {key:?} in {}", path.display()))
}
fn required_string_array(table: &toml::Table, key: &str, path: &Path) -> Vec<String> {
table
.get(key)
.and_then(toml::Value::as_array)
.unwrap_or_else(|| panic!("Missing array {key:?} in {}", path.display()))
.iter()
.map(|value| {
value
.as_str()
.unwrap_or_else(|| panic!("{key:?} must contain strings in {}", path.display()))
.to_owned()
})
.collect()
}
fn required_string_table(table: &toml::Table, key: &str, path: &Path) -> BTreeMap<String, String> {
table
.get(key)
.and_then(toml::Value::as_table)
.unwrap_or_else(|| panic!("Missing table {key:?} in {}", path.display()))
.iter()
.map(|(entry_key, value)| {
let value = value.as_str().unwrap_or_else(|| {
panic!("{key}.{entry_key} must be a string in {}", path.display())
});
(entry_key.clone(), value.to_owned())
})
.collect()
}
fn build_ui_fallback_subset() {
let codepoints = (' '..='~')
.chain(['\u{2014}', '\u{2018}', '\u{2019}'])
.collect::<BTreeSet<_>>();
let options = SubsetOptions::default()
.strip_hints(true)
.retain_layout_tables(false)
.retain_names(false)
.drop_variations(true);
let (subset, stats) = subset_font_with_options(UBUNTU_LIGHT, &codepoints, &options)
.expect("Failed to build the UI fallback font subset");
let output = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR was not set"))
.join("ui-fallback.ttf");
write_if_changed(&output, &subset)
.unwrap_or_else(|error| panic!("Failed to write {}: {error}", output.display()));
println!(
"cargo:warning=UI fallback font subset: {} characters, {} -> {} bytes",
codepoints.len(),
stats.original_size,
stats.subset_size
);
}
fn build_lucide_subset() {
println!("cargo:rerun-if-changed=src");
let mut source_files = Vec::new();
collect_rust_sources(Path::new("src"), &mut source_files)
.expect("Failed to enumerate Rust source files for Lucide icons");
let mut variants = BTreeSet::new();
for path in source_files {
let source = fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display()));
let tokens = source
.parse::<TokenStream>()
.unwrap_or_else(|error| panic!("Failed to tokenize {}: {error}", path.display()));
collect_lucide_variants(tokens, &mut variants);
}
assert!(
!variants.is_empty(),
"No LucideIcon::Variant references were found under src"
);
let codepoints = variants
.iter()
.map(|variant| {
let icon_name = variant.to_kebab_case();
LucideIcon::try_from(icon_name.as_str())
.unwrap_or_else(|error| panic!("Unknown Lucide icon variant {variant}: {error}"))
.unicode()
})
.collect::<BTreeSet<_>>();
let options = SubsetOptions::default()
.strip_hints(true)
.retain_layout_tables(false)
.retain_names(false)
.drop_variations(true);
let (subset, stats) = subset_font_with_options(LUCIDE_FONT_BYTES, &codepoints, &options)
.expect("Failed to build the Lucide icon font subset");
let output = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR was not set"))
.join("lucide-subset.ttf");
write_if_changed(&output, &subset)
.unwrap_or_else(|error| panic!("Failed to write {}: {error}", output.display()));
println!(
"cargo:warning=Lucide font subset: {} icons, {} -> {} bytes",
codepoints.len(),
stats.original_size,
stats.subset_size
);
}
fn collect_rust_sources(directory: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
for entry in fs::read_dir(directory)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
collect_rust_sources(&path, files)?;
} else if path.extension().is_some_and(|extension| extension == "rs") {
files.push(path);
}
}
Ok(())
}
fn write_if_changed(path: &Path, contents: &[u8]) -> std::io::Result<()> {
if fs::read(path).is_ok_and(|existing| existing == contents) {
return Ok(());
}
fs::write(path, contents)
}
fn collect_lucide_variants(tokens: TokenStream, variants: &mut BTreeSet<String>) {
let tokens = tokens.into_iter().collect::<Vec<_>>();
for window in tokens.windows(4) {
if let (
TokenTree::Ident(alias),
TokenTree::Punct(first_colon),
TokenTree::Punct(second_colon),
TokenTree::Ident(variant),
) = (&window[0], &window[1], &window[2], &window[3])
{
if alias == "LucideIcon"
&& first_colon.as_char() == ':'
&& second_colon.as_char() == ':'
{
variants.insert(variant.to_string());
}
}
}
for token in tokens {
if let TokenTree::Group(group) = token {
collect_lucide_variants(group.stream(), variants);
}
}
}
fn pack_version(version: &str) -> u64 {
let core = version.split('-').next().unwrap_or(version);
let mut parts = core.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
let major = parts.next().unwrap_or(0).min(u16::MAX as u64);
let minor = parts.next().unwrap_or(0).min(u16::MAX as u64);
let patch = parts.next().unwrap_or(0).min(u16::MAX as u64);
(major << 48) | (minor << 32) | (patch << 16)
}