day-toolchain 0.6.4

Shared host-toolchain and SDK discovery for Day's build scripts and CLI.
Documentation
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The Windows App SDK (WinUI 3) inputs a `windows-winui` build compiles against: the NuGet
//! packages' headers and runtime DLLs, and C++/WinRT projection headers generated from their
//! metadata (docs/winui.md).
//!
//! Nothing here is linked. The shim loads the bootstrapper and the one flat export it needs at
//! run time, so an app binary carries no import of a Windows App SDK DLL: that is what lets the
//! same exe start whether the bootstrapper sits next to it (a packaged app) or in this cache (a
//! development build).
//!
//! Resolution: `DAY_WINAPPSDK` (a directory already laid out as [`crate::winappsdk::WinAppSdk`] describes, for an
//! offline machine), else the per-user cache (`DAY_WINAPPSDK_CACHE`, default
//! `%LOCALAPPDATA%\day\winappsdk`), filled on first use from nuget.org with the in-box `curl` and
//! `tar`, the way day-piece-webview fetches its SDK. Pinned versions, so a build is reproducible;
//! the runtime they select is the 2.x framework package (`Microsoft.WindowsAppRuntime.2`) at
//! [`crate::winappsdk::RUNTIME_VERSION`] or newer.

use std::path::{Path, PathBuf};
use std::process::Command;

/// The Windows App SDK release the backend targets, as the bootstrapper's `major.minor`.
pub const RELEASE_MAJOR_MINOR: u32 = 0x0002_0005;

/// The Windows App SDK release the pinned packages belong to (the `Microsoft.WindowsAppSDK`
/// metapackage version), which is also the oldest runtime an app built with them accepts. From
/// 2.0 on, the framework package is one per major version, `Microsoft.WindowsAppRuntime.2`, and
/// its package version is this release number.
pub const RUNTIME_VERSION: &str = "2.5.1";

/// The framework package a framework-dependent app binds to.
pub const FRAMEWORK_PACKAGE: &str = "Microsoft.WindowsAppRuntime.2";

/// The component packages (id, version) a WinUI build needs: the framework's bootstrapper and
/// Microsoft.Windows.* metadata, `Microsoft.UI.Xaml`, and `Microsoft.UI` (windowing, content,
/// composition, dispatching). WebView2's metadata is referenced by `Microsoft.UI.Xaml`'s, so the
/// projection cannot be generated without it; the version is the one the WinUI package pins. The
/// component versions are the ones the `Microsoft.WindowsAppSDK` [`RUNTIME_VERSION`] metapackage
/// pins (from 2.0 on, each component is versioned on its own).
pub const PACKAGES: &[(&str, &str)] = &[
    ("microsoft.windowsappsdk.foundation", "2.3.12"),
    ("microsoft.windowsappsdk.winui", "2.3.9"),
    ("microsoft.windowsappsdk.interactiveexperiences", "2.1.9"),
    ("microsoft.web.webview2", "1.0.3719.77"),
    ("microsoft.graphics.win2d", "1.4.0"),
];

/// Where everything a WinUI shim build needs was found.
#[derive(Debug, Clone)]
pub struct WinAppSdk {
    /// The generated C++/WinRT projection for the Windows App SDK namespaces. Goes on the include
    /// path AHEAD of the Windows SDK's own cppwinrt directory, whose `base.h` it shares.
    pub projection: PathBuf,
    /// Native headers: `MddBootstrap.h` (foundation) and the interop headers
    /// (interactiveexperiences).
    pub includes: Vec<PathBuf>,
    /// `Microsoft.WindowsAppRuntime.Bootstrap.dll` for the target architecture.
    pub bootstrap_dll: PathBuf,
    /// Win2D's native implementation, deployed beside the executable.
    pub canvas_dll: PathBuf,
}

fn arch_dir(target_arch: &str) -> Result<&'static str, String> {
    match target_arch {
        "aarch64" => Ok("arm64"),
        "x86_64" => Ok("x64"),
        "x86" => Ok("x86"),
        other => Err(format!(
            "the Windows App SDK has no build for target arch {other:?}"
        )),
    }
}

/// The per-user cache root.
pub fn cache_root() -> PathBuf {
    if let Ok(v) = std::env::var("DAY_WINAPPSDK_CACHE") {
        return PathBuf::from(v);
    }
    let base = std::env::var("LOCALAPPDATA")
        .map(PathBuf::from)
        .unwrap_or_else(|_| std::env::temp_dir());
    base.join("day").join("winappsdk")
}

/// Resolve (downloading and generating on first use) everything a WinUI shim build needs.
///
/// `cppwinrt_include` is the Windows SDK's `Include\<version>\cppwinrt` the shim compiles with;
/// the projection is generated by the `cppwinrt.exe` of that SAME SDK version, because generated
/// headers must match the `base.h` they are compiled against.
pub fn resolve(cppwinrt_include: &Path, target_arch: &str) -> Result<WinAppSdk, String> {
    let arch = arch_dir(target_arch)?;
    let root = packages_root()?;
    // Cargo runs the backend and native-piece build scripts concurrently. Serialize
    // projection generation so none removes another process's partial output.
    let _projection_lock = cache_lock(&root, "projection")?;
    let pkg = |id: &str| package_dir(&root, id);
    let foundation = pkg("microsoft.windowsappsdk.foundation");
    let winui = pkg("microsoft.windowsappsdk.winui");
    let ie = pkg("microsoft.windowsappsdk.interactiveexperiences");
    let wv2 = pkg("microsoft.web.webview2");
    let win2d = pkg("microsoft.graphics.win2d");
    let canvas_dll = win2d
        .join("runtimes")
        .join(format!("win-{arch}"))
        .join("native/Microsoft.Graphics.Canvas.dll");
    if !canvas_dll.exists() {
        return Err(format!("{} is missing", canvas_dll.display()));
    }

    let bootstrap_dll = foundation
        .join("runtimes")
        .join(format!("win-{arch}"))
        .join("native")
        .join("Microsoft.WindowsAppRuntime.Bootstrap.dll");
    if !bootstrap_dll.exists() {
        return Err(format!("{} is missing", bootstrap_dll.display()));
    }

    // The projection, per SDK version: `Include\10.0.26100.0\cppwinrt` → `10.0.26100.0`.
    let sdk_version = cppwinrt_include
        .parent()
        .and_then(Path::file_name)
        .map(|v| v.to_string_lossy().into_owned())
        .ok_or_else(|| {
            format!(
                "cannot tell the SDK version of {}",
                cppwinrt_include.display()
            )
        })?;
    // Keyed on the WinUI package too: a projection generated from another release's metadata
    // would compile and then fail at activation.
    let winui_version = PACKAGES
        .iter()
        .find(|(id, _)| *id == "microsoft.windowsappsdk.winui")
        .map_or("", |(_, v)| *v);
    let projection = root.join(format!(
        "projection-{sdk_version}-winui{winui_version}-win2d1.4.0"
    ));
    if !projection
        .join("winrt")
        .join("Microsoft.UI.Xaml.Controls.h")
        .exists()
    {
        let exe = cppwinrt_exe(cppwinrt_include, &sdk_version)?;
        let staging = root.join(format!("projection-{sdk_version}.partial"));
        let _ = std::fs::remove_dir_all(&staging);
        let ie_meta = ie.join("metadata").join("10.0.18362.0");
        let status = Command::new(&exe)
            .arg("-in")
            .arg(winui.join("metadata"))
            .arg("-in")
            .arg(&ie_meta)
            .arg("-in")
            .arg(foundation.join("metadata"))
            .arg("-in")
            .arg(wv2.join("lib").join("Microsoft.Web.WebView2.Core.winmd"))
            .arg("-in")
            .arg(win2d.join("lib/uap10.0/Microsoft.Graphics.Canvas.winmd"))
            .args(["-ref", "sdk", "-out"])
            .arg(&staging)
            .status()
            .map_err(|e| format!("running {}: {e}", exe.display()))?;
        if !status.success() {
            return Err(format!("{} failed ({status})", exe.display()));
        }
        // Published by rename, so a build that died half-way never leaves a projection that
        // looks complete.
        let _ = std::fs::remove_dir_all(&projection);
        std::fs::rename(&staging, &projection)
            .map_err(|e| format!("publishing {}: {e}", projection.display()))?;
    }

    Ok(WinAppSdk {
        projection,
        includes: vec![foundation.join("include"), ie.join("include")],
        bootstrap_dll,
        canvas_dll,
    })
}

/// The directory holding the extracted packages, fetching any that are missing.
fn packages_root() -> Result<PathBuf, String> {
    match std::env::var("DAY_WINAPPSDK") {
        Ok(v) => Ok(PathBuf::from(v)),
        Err(_) => {
            let root = cache_root();
            for (id, version) in PACKAGES {
                fetch_package(&root, id, version)?;
            }
            Ok(root)
        }
    }
}

fn package_dir(root: &Path, id: &str) -> PathBuf {
    let version = PACKAGES
        .iter()
        .find(|(i, _)| *i == id)
        .map(|(_, v)| *v)
        .unwrap_or("");
    root.join(format!("{id}.{version}"))
}

// ---------------------------------------------------------------------------
// Self-contained deployment (docs/winui.md "Packing")
// ---------------------------------------------------------------------------
//
// What `WindowsAppSDKSelfContained=true` does in Microsoft's MSBuild targets
// (Microsoft.WindowsAppSDK.SelfContained.targets, in the Base package), done here for a cargo
// build: copy each component package's `runtimes-framework\win-<arch>\native` payload next to the
// exe, and merge a manifest that registers every WinRT class those DLLs implement, so Windows'
// registration-free WinRT activates them from the app's folder with no framework package and no
// bootstrapper. The shim notices the app-local runtime and skips the bootstrapper.

/// The component packages whose runtime a self-contained WinUI app carries. WebView2's package
/// is metadata only here (its loader ships with the WebView2 runtime).
const RUNTIME_PACKAGES: &[&str] = &[
    "microsoft.windowsappsdk.foundation",
    "microsoft.windowsappsdk.winui",
    "microsoft.windowsappsdk.interactiveexperiences",
];

/// The files a self-contained app carries beside its exe, as (source, path relative to the exe's
/// directory): the same selection the SDK's targets make (DLLs, resource indexes, compiled XAML,
/// localized strings, images, metadata).
pub fn self_contained_payload(target_arch: &str) -> Result<Vec<(PathBuf, PathBuf)>, String> {
    let arch = arch_dir(target_arch)?;
    let root = packages_root()?;
    let mut out = Vec::new();
    out.push((
        package_dir(&root, "microsoft.graphics.win2d")
            .join("runtimes")
            .join(format!("win-{arch}"))
            .join("native/Microsoft.Graphics.Canvas.dll"),
        PathBuf::from("Microsoft.Graphics.Canvas.dll"),
    ));
    for id in RUNTIME_PACKAGES {
        let pkg = package_dir(&root, id);
        let native = pkg
            .join("runtimes-framework")
            .join(format!("win-{arch}"))
            .join("native");
        walk(&native, &native, &mut |src, rel| {
            let name = rel.to_string_lossy().to_ascii_lowercase();
            let keep = [".dll", ".pri", ".xbf", ".xaml", ".mui", ".png", ".winmd"]
                .iter()
                .any(|ext| name.ends_with(ext))
                || name.ends_with("restartagent.exe")
                || name.ends_with("map.html")
                || (name.contains("workloads") && name.ends_with(".json"));
            if keep {
                out.push((src.to_path_buf(), rel.to_path_buf()));
            }
        })?;
        // The metadata the XAML runtime reads type information from.
        for meta in [
            pkg.join("metadata"),
            pkg.join("metadata").join("10.0.18362.0"),
        ] {
            let Ok(entries) = std::fs::read_dir(&meta) else {
                continue;
            };
            for e in entries.flatten() {
                let p = e.path();
                if p.extension()
                    .is_some_and(|x| x.eq_ignore_ascii_case("winmd"))
                {
                    out.push((p.clone(), PathBuf::from(e.file_name())));
                }
            }
        }
    }
    // WebView2Loader.dll: WinUI's WebView2 control loads it by name, and it is the app's to
    // supply, not part of the Windows App SDK runtime (day-piece-webview preloads it in a
    // development build).
    let loader = package_dir(&root, "microsoft.web.webview2")
        .join("runtimes")
        .join(format!("win-{arch}"))
        .join("native")
        .join("WebView2Loader.dll");
    if loader.exists() {
        out.push((loader, PathBuf::from("WebView2Loader.dll")));
    }
    // …and the control's WinRT core, which the WinUI registrations name by file name.
    let core = package_dir(&root, "microsoft.web.webview2")
        .join("runtimes")
        .join(format!("win-{arch}"))
        .join("native_uap")
        .join("Microsoft.Web.WebView2.Core.dll");
    if core.exists() {
        out.push((core, PathBuf::from("Microsoft.Web.WebView2.Core.dll")));
    }
    out.sort_by(|a, b| a.1.cmp(&b.1));
    out.dedup_by(|a, b| a.1 == b.1);
    Ok(out)
}

/// The manifest that registers the runtime's WinRT classes and proxy stubs for registration-free
/// activation, generated from each package's `package.appxfragment` the way the SDK's
/// `GenerateAppManifestFromAppxFragments` task does. Merge it into the exe's manifest (a second
/// `/MANIFESTINPUT`).
pub fn self_contained_manifest() -> Result<String, String> {
    let root = packages_root()?;
    let mut out = String::from(
        "<?xml version='1.0' encoding='utf-8' standalone='yes'?>\n\
         <assembly manifestVersion='1.0'\n    \
         xmlns:asmv3='urn:schemas-microsoft-com:asm.v3'\n    \
         xmlns:winrtv1='urn:schemas-microsoft-com:winrt.v1'\n    \
         xmlns='urn:schemas-microsoft-com:asm.v1'>\n",
    );
    for id in RUNTIME_PACKAGES {
        let fragment = package_dir(&root, id)
            .join("runtimes-framework")
            .join("package.appxfragment");
        let xml = std::fs::read_to_string(&fragment)
            .map_err(|e| format!("reading {}: {e}", fragment.display()))?;
        for server in elements(&xml, "InProcessServer") {
            let Some(dll) = element_text(server, "Path") else {
                continue;
            };
            out.push_str(&format!("    <asmv3:file name='{dll}'>\n"));
            for class in start_tags(server, "ActivatableClass") {
                if let Some(name) = attribute(class, "ActivatableClassId") {
                    out.push_str(&format!(
                        "        <winrtv1:activatableClass name='{name}' threadingModel='both'/>\n"
                    ));
                }
            }
            out.push_str("    </asmv3:file>\n");
        }
        for stub in elements(&xml, "ProxyStub") {
            let Some(dll) = element_text(stub, "Path") else {
                continue;
            };
            // The SDK's own exclusions: this one needs the push-notification singleton, which a
            // self-contained app does not have.
            if dll == "PushNotificationsLongRunningTask.ProxyStub.dll" {
                continue;
            }
            let Some(clsid) = attribute(stub, "ClassId") else {
                continue;
            };
            out.push_str(&format!("    <asmv3:file name='{dll}'>\n"));
            out.push_str(&format!("        <asmv3:comClass clsid='{{{clsid}}}'/>\n"));
            for iface in start_tags(stub, "Interface") {
                if let (Some(name), Some(iid)) =
                    (attribute(iface, "Name"), attribute(iface, "InterfaceId"))
                {
                    out.push_str(&format!(
                        "        <asmv3:comInterfaceProxyStub name='{name}' iid='{{{iid}}}'/>\n"
                    ));
                }
            }
            out.push_str("    </asmv3:file>\n");
        }
    }
    out.push_str("</assembly>\n");
    Ok(out)
}

/// Merge the runtime's resource indexes in `payload` (the staged exe's directory) into the
/// `resources.pri` a self-contained app resolves `ms-appx:///` through.
///
/// A framework-dependent app gets this index from the framework package. A self-contained one has
/// to carry its own, or WinUI cannot load its control templates
/// (`ms-appx:///Microsoft.UI.Xaml/Themes/themeresources.xaml`) and the window never opens. The
/// SDK's MSBuild targets build it with makepri from the component `.pri` files; so does this:
/// the `.pri` files are listed in a `.resfiles` file and indexed with the `PRI` indexer.
pub fn merge_resource_indexes(payload: &Path, scratch: &Path) -> Result<(), String> {
    // makepri takes backslashes only, and a project root can arrive with a `/` in it.
    let native = |p: &Path| PathBuf::from(p.to_string_lossy().replace('/', "\\"));
    let (payload, scratch) = (native(payload), native(scratch));
    let (payload, scratch) = (payload.as_path(), scratch.as_path());
    let makepri = crate::windows_kit_tool("makepri.exe")
        .ok_or("makepri.exe not found (it ships with the Windows 10/11 SDK)")?;
    let _ = std::fs::remove_dir_all(scratch);
    std::fs::create_dir_all(scratch).map_err(|e| format!("creating {}: {e}", scratch.display()))?;
    let mut names = Vec::new();
    let entries =
        std::fs::read_dir(payload).map_err(|e| format!("reading {}: {e}", payload.display()))?;
    for e in entries.flatten() {
        let name = e.file_name().to_string_lossy().into_owned();
        if name.to_ascii_lowercase().ends_with(".pri")
            && !name.eq_ignore_ascii_case("resources.pri")
        {
            std::fs::copy(e.path(), scratch.join(&name)).map_err(|e| e.to_string())?;
            names.push(name);
        }
    }
    if names.is_empty() {
        return Err(format!("no .pri files in {}", payload.display()));
    }
    names.sort();
    // One name per LF-terminated line: makepri does not split on CRLF, and read a CRLF list as a
    // single file name.
    let list: String = names.iter().map(|n| format!("{n}\n")).collect();
    std::fs::write(scratch.join("pri.resfiles"), list).map_err(|e| e.to_string())?;
    let config = scratch.join("priconfig.xml");
    std::fs::write(&config, PRI_MERGE_CONFIG).map_err(|e| e.to_string())?;
    let out = Command::new(&makepri)
        .arg("new")
        .arg("/pr")
        .arg(scratch)
        .arg("/cf")
        .arg(&config)
        .arg("/of")
        .arg(payload.join("resources.pri"))
        .args(["/in", "DayApp", "/o"])
        .output()
        .map_err(|e| format!("running {}: {e}", makepri.display()))?;
    if !out.status.success() {
        // makepri writes UTF-16, and its errors to stderr; the lossy form is readable enough.
        let text = |b: &[u8]| String::from_utf8_lossy(b).replace('\0', "");
        return Err(format!(
            "makepri failed: {}{}",
            text(&out.stdout).trim(),
            text(&out.stderr).trim()
        ));
    }
    Ok(())
}

const PRI_MERGE_CONFIG: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<resources targetOsVersion="10.0.0" majorVersion="1">
  <index root="\" startIndexAt="pri.resfiles">
    <default>
      <qualifier name="Language" value="en-US"/>
      <qualifier name="Contrast" value="standard"/>
      <qualifier name="Scale" value="100"/>
      <qualifier name="HomeRegion" value="001"/>
      <qualifier name="TargetSize" value="256"/>
      <qualifier name="LayoutDirection" value="LTR"/>
      <qualifier name="Theme" value="dark"/>
      <qualifier name="AlternateForm" value=""/>
      <qualifier name="DXFeatureLevel" value="DX9"/>
      <qualifier name="Configuration" value=""/>
      <qualifier name="DeviceFamily" value="Universal"/>
      <qualifier name="Custom" value=""/>
    </default>
    <indexer-config type="RESFILES" qualifierDelimiter="."/>
    <indexer-config type="PRI"/>
  </index>
</resources>
"#;

fn walk(base: &Path, dir: &Path, f: &mut dyn FnMut(&Path, &Path)) -> Result<(), String> {
    let entries = std::fs::read_dir(dir).map_err(|e| format!("reading {}: {e}", dir.display()))?;
    for e in entries.flatten() {
        let p = e.path();
        if p.is_dir() {
            walk(base, &p, f)?;
        } else if let Ok(rel) = p.strip_prefix(base) {
            f(&p, rel);
        }
    }
    Ok(())
}

// A fragment is small, machine-written XML with no nesting of the elements read here, so a
// scan is enough and keeps this crate dependency-free.

/// Every `<tag …>…</tag>` element, as its full text.
fn elements<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> {
    let (open, close) = (format!("<{tag}"), format!("</{tag}>"));
    let mut out = Vec::new();
    let mut rest = xml;
    while let Some(start) = rest.find(&open) {
        let after = &rest[start..];
        // `<ProxyStub` must not match `<ProxyStubX`.
        if !after[open.len()..].starts_with([' ', '>', '\r', '\n', '\t']) {
            rest = &after[open.len()..];
            continue;
        }
        let Some(end) = after.find(&close) else { break };
        out.push(&after[..end + close.len()]);
        rest = &after[end + close.len()..];
    }
    out
}

/// Every `<tag …>` or `<tag …/>` start tag.
fn start_tags<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> {
    let open = format!("<{tag}");
    let mut out = Vec::new();
    let mut rest = xml;
    while let Some(start) = rest.find(&open) {
        let after = &rest[start..];
        let Some(end) = after.find('>') else { break };
        if after[open.len()..].starts_with([' ', '>', '/', '\r', '\n', '\t']) {
            out.push(&after[..=end]);
        }
        rest = &after[end + 1..];
    }
    out
}

fn element_text<'a>(xml: &'a str, tag: &str) -> Option<&'a str> {
    let open = format!("<{tag}>");
    let start = xml.find(&open)? + open.len();
    let end = xml[start..].find(&format!("</{tag}>"))?;
    Some(xml[start..start + end].trim())
}

fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
    let key = format!("{name}=\"");
    let start = tag.find(&key)? + key.len();
    let end = tag[start..].find('"')?;
    Some(&tag[start..start + end])
}

/// The include path for a piece's XAML shim (docs/winui.md "Pieces"): the SDK's cppwinrt
/// directory alone for `windows-xaml`, and for `windows-winui` (the piece's `winui` feature) the
/// generated Windows App SDK projection and headers AHEAD of it, since the projection shares that
/// directory's base.h. The shim picks its namespace aliases from `DAY_WINUI`, as day-toolkit-xaml-sys does.
///
/// In a build script: `.includes(shim_includes(&cppwinrt))` where it used to add `cppwinrt`, and
/// `if shim_is_winui() { build.define("DAY_WINUI", None); }` before compiling.
pub fn shim_includes(cppwinrt_include: &Path) -> Vec<PathBuf> {
    if !shim_is_winui() {
        return vec![cppwinrt_include.to_path_buf()];
    }
    let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
    let sdk = resolve_for_build_script(cppwinrt_include, &arch)
        .unwrap_or_else(|e| panic!("the Windows App SDK (winui): {e}"));
    let mut includes = vec![sdk.projection];
    includes.extend(sdk.includes);
    includes.push(cppwinrt_include.to_path_buf());
    includes
}

/// Whether this build script is compiling for `windows-winui`: the crate's `winui` feature.
pub fn shim_is_winui() -> bool {
    std::env::var("CARGO_FEATURE_WINUI").is_ok()
}

/// [`resolve`] for build scripts: also emits the `rerun-if-env-changed` lines.
pub fn resolve_for_build_script(
    cppwinrt_include: &Path,
    target_arch: &str,
) -> Result<WinAppSdk, String> {
    for var in ["DAY_WINAPPSDK", "DAY_WINAPPSDK_CACHE"] {
        println!("cargo:rerun-if-env-changed={var}");
    }
    resolve(cppwinrt_include, target_arch)
}

/// The SDK's `cppwinrt.exe` next to `Include\<version>`: `bin\<version>\<host arch>`.
fn cppwinrt_exe(cppwinrt_include: &Path, sdk_version: &str) -> Result<PathBuf, String> {
    let kits = cppwinrt_include
        .parent()
        .and_then(Path::parent)
        .and_then(Path::parent)
        .ok_or_else(|| {
            format!(
                "{} is not under a Windows Kits root",
                cppwinrt_include.display()
            )
        })?;
    let hosts: &[&str] = if cfg!(target_arch = "aarch64") {
        &["arm64", "x64", "x86"]
    } else {
        &["x64", "x86"]
    };
    for host in hosts {
        let exe = kits
            .join("bin")
            .join(sdk_version)
            .join(host)
            .join("cppwinrt.exe");
        if exe.exists() {
            return Ok(exe);
        }
    }
    Err(format!(
        "no cppwinrt.exe for Windows SDK {sdk_version} under {}",
        kits.join("bin").display()
    ))
}

/// Make `<root>/<id>.<version>` hold the extracted package: the NuGet global cache's copy if the
/// machine has one, else a download from nuget.org.
fn fetch_package(root: &Path, id: &str, version: &str) -> Result<(), String> {
    let _package_lock = cache_lock(root, &format!("{id}.{version}"))?;
    let dest = root.join(format!("{id}.{version}"));
    if dest.join(".complete").exists() {
        return Ok(());
    }
    std::fs::create_dir_all(root).map_err(|e| format!("creating {}: {e}", root.display()))?;
    let staging = root.join(format!("{id}.{version}.partial"));
    let _ = std::fs::remove_dir_all(&staging);
    std::fs::create_dir_all(&staging)
        .map_err(|e| format!("creating {}: {e}", staging.display()))?;

    let nuget_cache = std::env::var("NUGET_PACKAGES")
        .map(PathBuf::from)
        .or_else(|_| {
            std::env::var("USERPROFILE").map(|h| PathBuf::from(h).join(".nuget").join("packages"))
        })
        .ok()
        .map(|p| p.join(id).join(version))
        .filter(|p| p.is_dir());
    if let Some(src) = nuget_cache {
        copy_dir(&src, &staging).map_err(|e| format!("copying {}: {e}", src.display()))?;
    } else {
        // A .nupkg is an OPC zip, which the in-box bsdtar extracts.
        let nupkg = root.join(format!("{id}.{version}.nupkg"));
        let url =
            format!("https://api.nuget.org/v3-flatcontainer/{id}/{version}/{id}.{version}.nupkg");
        run("curl", &["-sSfL", "-o", &nupkg.to_string_lossy(), &url])?;
        run(
            "tar",
            &[
                "-xf",
                &nupkg.to_string_lossy(),
                "-C",
                &staging.to_string_lossy(),
            ],
        )?;
        let _ = std::fs::remove_file(&nupkg);
    }
    std::fs::write(staging.join(".complete"), b"").map_err(|e| e.to_string())?;
    let _ = std::fs::remove_dir_all(&dest);
    std::fs::rename(&staging, &dest).map_err(|e| format!("publishing {}: {e}", dest.display()))
}

fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(to)?;
    for entry in std::fs::read_dir(from)? {
        let entry = entry?;
        let target = to.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir(&entry.path(), &target)?;
        } else {
            std::fs::copy(entry.path(), target)?;
        }
    }
    Ok(())
}

// The OS releases the lock if a build script exits or crashes. Keep the lock file:
// deleting it would let another process lock a different file at the same path.
fn cache_lock(root: &Path, name: &str) -> Result<std::fs::File, String> {
    std::fs::create_dir_all(root).map_err(|e| format!("creating {}: {e}", root.display()))?;
    let path = root.join(format!("{name}.lock"));
    let file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&path)
        .map_err(|e| format!("opening {}: {e}", path.display()))?;
    file.lock()
        .map_err(|e| format!("locking {}: {e}", path.display()))?;
    Ok(file)
}

fn run(cmd: &str, args: &[&str]) -> Result<(), String> {
    let out = Command::new(cmd)
        .args(args)
        .output()
        .map_err(|e| format!("running {cmd}: {e}"))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(format!(
            "{cmd} {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cache_publishers_are_serialized() {
        let root = std::env::temp_dir().join(format!(
            "day-winappsdk-lock-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("count"), "0").unwrap();
        std::thread::scope(|scope| {
            for _ in 0..8 {
                let root = &root;
                scope.spawn(move || {
                    for _ in 0..10 {
                        let _lock = cache_lock(root, "package").unwrap();
                        let count: usize = std::fs::read_to_string(root.join("count"))
                            .unwrap()
                            .parse()
                            .unwrap();
                        std::thread::yield_now();
                        std::fs::write(root.join("count"), (count + 1).to_string()).unwrap();
                    }
                });
            }
        });
        assert_eq!(std::fs::read_to_string(root.join("count")).unwrap(), "80");
        std::fs::remove_dir_all(root).unwrap();
    }

    const FRAGMENT: &str = r#"<Fragment><Extensions>
  <Extension Category="windows.activatableClass.inProcessServer">
    <InProcessServer>
      <Path>Microsoft.UI.Xaml.dll</Path>
      <ActivatableClass ActivatableClassId="Microsoft.UI.Xaml.Application" ThreadingModel="both" />
      <ActivatableClass ActivatableClassId="Microsoft.UI.Xaml.Window" ThreadingModel="both" />
    </InProcessServer>
  </Extension>
  <Extension Category="windows.activatableClass.proxyStub">
    <ProxyStub ClassId="71201C0F-21E1-4B80-945F-7B0A10F90883">
      <Path>Microsoft.WindowsAppRuntime.dll</Path>
      <Interface Name="IFoo" InterfaceId="11111111-2222-3333-4444-555555555555" />
    </ProxyStub>
  </Extension>
</Extensions></Fragment>"#;

    #[test]
    fn fragments_yield_servers_classes_and_stubs() {
        let servers = elements(FRAGMENT, "InProcessServer");
        assert_eq!(servers.len(), 1);
        assert_eq!(
            element_text(servers[0], "Path"),
            Some("Microsoft.UI.Xaml.dll")
        );
        let classes: Vec<_> = start_tags(servers[0], "ActivatableClass")
            .into_iter()
            .filter_map(|t| attribute(t, "ActivatableClassId"))
            .collect();
        assert_eq!(
            classes,
            ["Microsoft.UI.Xaml.Application", "Microsoft.UI.Xaml.Window"]
        );
        let stubs = elements(FRAGMENT, "ProxyStub");
        assert_eq!(stubs.len(), 1);
        assert_eq!(
            attribute(stubs[0], "ClassId"),
            Some("71201C0F-21E1-4B80-945F-7B0A10F90883")
        );
        let ifaces = start_tags(stubs[0], "Interface");
        assert_eq!(
            attribute(ifaces[0], "InterfaceId"),
            Some("11111111-2222-3333-4444-555555555555")
        );
    }
}