day-cli 0.1.4

Declarative app development API using native UI toolkits
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
//! Build / launch operations. Desktop = cargo with per-(target, profile) CARGO_TARGET_DIR
//! (§16.5 — parallel targets never contend on the cargo build-dir lock). Mobile pipelines
//! attach here at M5 (xcodebuild + simctl; gradle + adb).

use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::{Command, Stdio};

use crate::meta::Project;
use crate::targets::{Target, TargetKind};
use crate::term::{HEADER, LOG_ERR, LOG_OUT};

pub struct BuildOutcome {
    pub target: &'static str,
    pub artifact: PathBuf,
    pub seconds: f64,
}

pub(crate) fn cargo_dir(project: &Project, target: &Target, profile: &str) -> PathBuf {
    project
        .root
        .join("build/day/cargo")
        .join(target.name)
        .join(profile)
}

pub fn status(prefix: &str, msg: &str) {
    anstream::eprintln!("{HEADER}{prefix:>12}{HEADER:#} {msg}");
}

/// Export the app identity (Day.toml `[app]`) to a cargo/build or launch command. day-break's
/// `build.rs` bakes these into the binary so crash reports carry id/version/build without
/// reading platform manifests at runtime (docs/break.md); on launch commands they double as the
/// runtime fallback for dev flows whose binary predates the vars.
pub fn apply_app_identity(cmd: &mut Command, project: &Project) {
    cmd.env("DAY_APP_ID", &project.manifest.app.id)
        .env("DAY_APP_VERSION", &project.manifest.app.version)
        .env("DAY_APP_BUILD", project.manifest.app.build.to_string());
    apply_determinism(cmd);
}

/// Environment that makes Apple's toolchain stop stamping the clock into its output
/// (DESIGN.md §20.3).
///
/// `libtool` and `ld64` write file modification times into static archives and into the debug map's
/// `OSO` entries, so two builds of identical sources differ by whenever they happened to run.
/// `ZERO_AR_DATE` zeroes both. It is set here rather than in CI so local packs are deterministic
/// too — reproducibility that only holds on the build farm is not worth much.
///
/// Scope: archive and debug-map timestamps only. It does NOT touch `__DATE__`/`__TIME__` (Day uses
/// neither), and it is inert on non-Apple hosts.
pub fn apply_determinism(cmd: &mut Command) {
    cmd.env("ZERO_AR_DATE", "1");
    // Export the resolved epoch so any SOURCE_DATE_EPOCH-aware tool downstream agrees with the
    // value Day stamps into archives itself — flatpak-builder honours it (1.3.1+), as do many
    // compilers and archivers. Passing through the caller's value when they set one, and Day's
    // default otherwise, means one clock governs the whole pack.
    cmd.env(
        "SOURCE_DATE_EPOCH",
        crate::pack::reproducible_epoch().to_string(),
    );
}

/// The comma-joined `--features` string for a `backend` toolkit: the toolkit feature itself plus the
/// unioned `<pkg>/<backend>` renderer feature of every standalone piece in the app's dependency
/// closure (Tier A.2 — apps no longer fan out per-piece features in their own Cargo.toml).
pub fn feature_selection(project: &Project, backend: &str) -> String {
    let mut features = vec![backend.to_string()];
    features.extend(crate::pieces::feature_union(project, backend));
    features.join(",")
}

/// Where [`build`] records the last successful artifact path for a (target, profile) — the
/// `--skip-build` reuse stamp. One line, the absolute artifact path.
fn artifact_stamp(project: &Project, target: &Target, profile: &str) -> PathBuf {
    project
        .root
        .join("build/day/artifacts")
        .join(format!("{}-{profile}.path", target.name))
}

/// Reuse the previous [`build`]'s artifact instead of building (`day launch --skip-build`):
/// the artifact is read from the stamp and must still exist. For runs whose variants share one
/// binary (theme/locale are runtime inputs), this drops the per-invocation build overhead —
/// CI's iOS walkthrough pays xcodebuild once instead of once per variant.
pub fn reuse_build(
    project: &Project,
    target: &'static Target,
    profile: &str,
) -> Result<BuildOutcome, String> {
    let stamp = artifact_stamp(project, target, profile);
    let artifact = std::fs::read_to_string(&stamp)
        .ok()
        .map(|s| PathBuf::from(s.trim()))
        .filter(|p| p.exists())
        .ok_or_else(|| {
            format!(
                "--skip-build: no reusable {} {profile} artifact — build once without the flag first",
                target.name
            )
        })?;
    status(
        "Reusing",
        &format!("{}{}", target.name, artifact.display()),
    );
    Ok(BuildOutcome {
        target: target.name,
        artifact,
        seconds: 0.0,
    })
}

pub fn build(
    project: &Project,
    target: &'static Target,
    profile: &str,
) -> Result<BuildOutcome, String> {
    let host = crate::targets::host_os();
    if target.host != "any" && target.host != host {
        return Err(format!(
            "target {} builds on a {} host (this is {})",
            target.name, target.host, host
        ));
    }
    let start = std::time::Instant::now();
    // Stage declared resources (images/ + assets/) into this target's native locations before its
    // platform build runs, so actool/aapt2/rcc/hvigor can process them (§18.3). Best-effort: this
    // needs the toolkit's native resource compiler (rcc / glib-compile-resources / …), which isn't
    // always on PATH (e.g. MSYS2 windows-qt/windows-gtk ship no rcc/glib-compile-resources). When
    // it's missing the resource blob is simply skipped — day loads assets from the filesystem roots
    // (DAY_IMAGE_ROOT) and the app icon rides DAY_APP_ICON — so a missing tool must NOT fail the build.
    if let Err(e) = crate::resources::stage(project, target) {
        status("Warning", &format!("resource staging skipped ({e})"));
    }
    let outcome = match target.kind {
        TargetKind::Desktop => {
            let mut cmd = Command::new("cargo");
            cmd.current_dir(&project.root)
                .env("CARGO_TARGET_DIR", cargo_dir(project, target, profile));
            apply_app_identity(&mut cmd, project);
            // Thinned ICU locale data for the declared locale set (crates/day-cli/src/intl.rs).
            crate::intl::apply(&mut cmd, project);
            // The toolkit feature (e.g. `appkit`) + every standalone piece's `<pkg>/<toolkit>`
            // renderer feature, derived from `cargo metadata` — so the app depends on a piece
            // without re-listing its per-backend feature (Tier A.2).
            let features = feature_selection(project, target.toolkit);
            if target.toolkit == "xaml" {
                // XAML Islands refuses to start unless the app manifest declares
                // `maxversiontested` (§9). rustc's default embedded manifest lacks it, so we
                // embed our own — `cargo rustc -- <link-args>` scopes this to the bin only.
                let manifest = write_xaml_manifest(project, target, profile)?;
                cmd.args(["rustc", "--bin", &project.manifest.app.name])
                    .args(["--no-default-features", "--features", &features]);
                if profile == "release" {
                    cmd.arg("--release");
                }
                cmd.arg("--");
                cmd.arg("-Clink-arg=/MANIFEST:EMBED");
                cmd.arg(format!("-Clink-arg=/MANIFESTINPUT:{}", manifest.display()));
                // Reproducible PE output (§20.3): without this the linker stamps the COFF header
                // and the debug directory with the wall clock, so the same commit built twice
                // differs by exactly those bytes and nothing else. `/Brepro` substitutes a hash of
                // the input, which is what makes the .exe comparable across builds. It rides here
                // rather than in RUSTFLAGS because CI already sets RUSTFLAGS and appending to an
                // inherited value is easy to get wrong; `cargo rustc --` scopes it to this bin.
                cmd.arg("-Clink-arg=/Brepro");
            } else {
                cmd.args([
                    "build",
                    "-p",
                    &project.manifest.app.name,
                    "--no-default-features",
                ])
                .args(["--features", &features]);
                if profile == "release" {
                    cmd.arg("--release");
                }
            }
            status("Building", &format!("{} ({})", target.name, profile));
            let out = cmd.status().map_err(|e| format!("cargo: {e}"))?;
            if !out.success() {
                return Err(format!("cargo build failed for {}", target.name));
            }
            // The desktop binary carries the platform's executable extension (`.exe` on Windows,
            // none elsewhere). `day launch`'s `Command::new` auto-appends it on Windows, but the raw
            // `fs::copy` in `pack` (msix/nsis stage the exe) needs the REAL path — so bake it in here.
            let artifact = cargo_dir(project, target, profile)
                .join(profile)
                .join(format!(
                    "{}{}",
                    project.manifest.app.name,
                    std::env::consts::EXE_SUFFIX
                ));
            Ok(BuildOutcome {
                target: target.name,
                artifact,
                seconds: start.elapsed().as_secs_f64(),
            })
        }
        TargetKind::IosSim => crate::mobile::build_ios(project, target, profile, start),
        TargetKind::Android => crate::mobile::build_android(project, target, profile, start),
        TargetKind::HarmonyOs => crate::ohos::build_ohos(project, target, profile, start),
        TargetKind::Web => crate::web::build_web(project, target, profile, start),
    }?;
    // Record the artifact for `--skip-build` reuse ([`reuse_build`]). Best-effort — a failed
    // stamp write must never fail a successful build.
    let stamp = artifact_stamp(project, target, profile);
    if let Some(dir) = stamp.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    let _ = std::fs::write(&stamp, outcome.artifact.display().to_string());
    Ok(outcome)
}

/// Side-by-side manifest that lets an unpackaged app host `Windows.UI.Xaml` islands (§9).
/// The `maxversiontested` element is the specific thing `WindowsXamlManager` demands.
const XAML_MANIFEST: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- Windows 10 and Windows 11 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
      <maxversiontested Id="10.0.22621.0"/>
    </application>
  </compatibility>
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
    </windowsSettings>
  </application>
</assembly>
"#;

fn write_xaml_manifest(
    project: &Project,
    target: &Target,
    profile: &str,
) -> Result<PathBuf, String> {
    let dir = cargo_dir(project, target, profile);
    std::fs::create_dir_all(&dir).map_err(|e| format!("manifest dir: {e}"))?;
    let path = dir.join("day-xaml.manifest");
    std::fs::write(&path, XAML_MANIFEST).map_err(|e| format!("manifest write: {e}"))?;
    Ok(path)
}

#[derive(Clone)]
pub struct LaunchSpec {
    pub locale: Option<String>,
    pub envs: Vec<(String, String)>,
    pub attached: bool,
    /// Which device to launch on, when the target has more than one. Today that means an iOS
    /// simulator (UDID or name): without it a launch goes to EVERY booted simulator, which is
    /// right for a capture sweep and wrong for anything that means one specific device — a
    /// side-by-side comparison against another app, or a machine that keeps several sims booted.
    /// `None` keeps the every-booted-simulator behaviour. Android already selects with
    /// `ANDROID_SERIAL`, which adb reads directly.
    pub device: Option<String>,
}

/// Launch a built artifact; returns a join handle streaming prefixed logs.
pub fn launch(
    project: &Project,
    target: &'static Target,
    outcome: &BuildOutcome,
    spec: &LaunchSpec,
) -> Result<std::thread::JoinHandle<i32>, String> {
    match target.kind {
        TargetKind::Desktop => {
            // Headless CI (a linux host with no display server): give the toolkit what the CI
            // shims used to wrap around the CLI — linux-gtk under xvfb sized to `[window]` (the
            // root-capture screenshot fallback then frames exactly the app) plus the WebKit
            // flags, linux-qt on the offscreen platform. This knowledge lived in TWO workflow
            // files (day's ci.yml and build-day-app.yml) and drifted between them; the CLI
            // knows the target and the window, so it decides.
            let wrap = headless_wrap(
                target.toolkit,
                crate::targets::host_os(),
                std::env::var_os("DISPLAY").is_some()
                    || std::env::var_os("WAYLAND_DISPLAY").is_some(),
                project.manifest.window.width,
                project.manifest.window.height,
            );
            let mut cmd = match &wrap {
                HeadlessWrap::Xvfb { width, height } => {
                    // Probe rather than assume: without xvfb-run the bare run at least fails
                    // with the toolkit's own display error, which is more actionable than
                    // "No such file or directory" from the wrapper.
                    if Command::new("xvfb-run").arg("--help").output().is_ok() {
                        status("Headless", "wrapping in xvfb-run (no DISPLAY on this host)");
                        let mut c = Command::new("xvfb-run");
                        c.args(["-a", "-s", &format!("-screen 0 {width}x{height}x24")])
                            .arg(&outcome.artifact)
                            .env("WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS", "1")
                            .env("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
                        c
                    } else {
                        status("Warning", "no DISPLAY and no xvfb-run — launching bare");
                        Command::new(&outcome.artifact)
                    }
                }
                HeadlessWrap::QtOffscreen => {
                    status(
                        "Headless",
                        "QT_QPA_PLATFORM=offscreen (no DISPLAY on this host)",
                    );
                    let mut c = Command::new(&outcome.artifact);
                    c.env("QT_QPA_PLATFORM", "offscreen");
                    c
                }
                HeadlessWrap::None => Command::new(&outcome.artifact),
            };
            cmd.current_dir(&project.root)
                .env("DAY_ASSET_ROOT", project.root.join("resource/assets"))
                .env("DAY_IMAGE_ROOT", project.root.join("resource/images"))
                // Bundled fonts (§18.4): the desktop backends register every file in this
                // directory with the platform font system at startup.
                .env("DAY_FONT_ROOT", project.root.join("resource/fonts"));
            apply_app_identity(&mut cmd, project);
            if spec.attached {
                cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
            } else {
                // Detached: the day process exits after spawning — piped stdio would close
                // with it and the app's next log write would die on SIGPIPE. The app must also
                // leave day's PROCESS GROUP: task runners (VS Code) dispose the pty when the
                // task's root process exits, and the resulting SIGHUP to the pty's foreground
                // group would kill a keep-alive app that stayed in it.
                cmd.stdout(Stdio::null()).stderr(Stdio::null());
                #[cfg(unix)]
                {
                    use std::os::unix::process::CommandExt;
                    cmd.process_group(0);
                }
                #[cfg(windows)]
                {
                    use std::os::windows::process::CommandExt;
                    const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
                    cmd.creation_flags(CREATE_NEW_PROCESS_GROUP);
                }
            }
            // App icon (§18.2): the backend applies it to the dock / taskbar at startup
            // (NSApp icon, QApplication window icon, GTK icon theme, Win32 WM_SETICON).
            if let Some(icon) = crate::resources::app_icon(project, target.toolkit) {
                cmd.env("DAY_APP_ICON", &icon);
                if target.toolkit == "gtk" && cfg!(target_os = "linux") {
                    // GTK4 window icons are THEMED-name only: stage the icon into a hicolor
                    // layout keyed by the app id and point the backend's icon-theme search at it.
                    let theme = project.root.join("build/day/gtk/icons");
                    let apps = theme.join("hicolor/512x512/apps");
                    let _ = std::fs::create_dir_all(&apps);
                    let name = &project.manifest.app.id;
                    if std::fs::copy(&icon, apps.join(format!("{name}.png"))).is_ok() {
                        cmd.env("DAY_ICON_THEME_DIR", &theme);
                        cmd.env("DAY_ICON_NAME", name);
                    }
                }
            }
            if target.toolkit == "gtk" {
                cmd.env("GSK_RENDERER", "cairo");
                // Native GResource blob (§18.3) — day-gtk registers it + loads via g_resources_*.
                let g = crate::resources::gtk::gresource_path(project);
                if g.exists() {
                    cmd.env("DAY_GRESOURCE", g);
                }
            }
            if target.toolkit == "qt" {
                // Native Qt resource blob (§18.3) — the day-qt shim registers it (QResource).
                let q = crate::resources::qt::qresource_path(project);
                if q.exists() {
                    cmd.env("DAY_QRESOURCE", q);
                }
            }
            if let Some(locale) = &spec.locale {
                cmd.env("DAY_LOCALE", locale);
            }
            for (k, v) in &spec.envs {
                cmd.env(k, v);
            }
            status("Launching", target.name);
            let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?;
            crate::signals::register_child(child.id());
            let name = target.name;
            let stdout = child.stdout.take();
            let stderr = child.stderr.take();
            let h = std::thread::spawn(move || {
                let t1 = stdout.map(|s| stream_logs(name, LogStream::Out, s));
                let t2 = stderr.map(|s| stream_logs(name, LogStream::Err, s));
                let code = child.wait().map(|s| s.code().unwrap_or(0)).unwrap_or(1);
                if let Some(t) = t1 {
                    let _ = t.join();
                }
                if let Some(t) = t2 {
                    let _ = t.join();
                }
                code
            });
            Ok(h)
        }
        TargetKind::IosSim => crate::mobile::launch_ios(project, outcome, spec),
        TargetKind::Android => crate::mobile::launch_android(project, outcome, spec),
        TargetKind::HarmonyOs => crate::ohos::launch_ohos(project, outcome, spec),
        TargetKind::Web => crate::web::launch_web(project, outcome, spec),
    }
}

/// Which standard stream a forwarded line came from — sets its colour and destination.
#[derive(Clone, Copy)]
pub enum LogStream {
    /// App stdout: blue, forwarded to our stdout.
    Out,
    /// App stderr: yellow, forwarded to our stderr.
    Err,
}

/// Print one already-classified log line with the `[target]` prefix and stream colour.
/// Public so the mobile log pumps (logcat/simctl) can reuse the exact formatting.
pub fn emit_log(name: &str, stream: LogStream, line: &str) {
    match stream {
        // 34 = blue, 33 = yellow; the whole line is coloured so streams read apart at a glance.
        LogStream::Out => anstream::println!("{LOG_OUT}[{name}]{LOG_OUT:#} {line}"),
        LogStream::Err => anstream::eprintln!("{LOG_ERR}[{name}]{LOG_ERR:#} {line}"),
    }
}

pub fn stream_logs(
    name: &'static str,
    stream: LogStream,
    src: impl std::io::Read + Send + 'static,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        for line in BufReader::new(src).lines().map_while(Result::ok) {
            emit_log(name, stream, &line);
        }
    })
}

/// How to run a desktop target on a host with no display server.
#[derive(Debug, PartialEq)]
pub(crate) enum HeadlessWrap {
    None,
    Xvfb { width: u32, height: u32 },
    QtOffscreen,
}

/// The decision alone, display-state and host passed in — testable on any machine. Only the
/// in-repo linux toolkits get house treatment; an external toolkit (docs/extending.md) manages
/// its own headless story.
pub(crate) fn headless_wrap(
    toolkit: &str,
    host: &str,
    display_present: bool,
    width: f64,
    height: f64,
) -> HeadlessWrap {
    if host != "linux" || display_present {
        return HeadlessWrap::None;
    }
    match toolkit {
        "gtk" => HeadlessWrap::Xvfb {
            width: width.max(1.0) as u32,
            height: height.max(1.0) as u32,
        },
        "qt" => HeadlessWrap::QtOffscreen,
        _ => HeadlessWrap::None,
    }
}

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

    #[test]
    fn linux_without_a_display_wraps_gtk_and_offscreens_qt() {
        assert_eq!(
            headless_wrap("gtk", "linux", false, 960.0, 640.0),
            HeadlessWrap::Xvfb {
                width: 960,
                height: 640
            }
        );
        assert_eq!(
            headless_wrap("qt", "linux", false, 960.0, 640.0),
            HeadlessWrap::QtOffscreen
        );
    }

    #[test]
    fn a_display_or_a_nonlinux_host_or_a_foreign_toolkit_runs_bare() {
        assert_eq!(
            headless_wrap("gtk", "linux", true, 1.0, 1.0),
            HeadlessWrap::None
        );
        assert_eq!(
            headless_wrap("gtk", "macos", false, 1.0, 1.0),
            HeadlessWrap::None
        );
        // External toolkits (Stage 0) own their headless behaviour.
        assert_eq!(
            headless_wrap("wxwidgets", "linux", false, 1.0, 1.0),
            HeadlessWrap::None
        );
    }
}