Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor 0fdf358ba5 fix(packaging): fix nightly-sign actionlint and address review comments
- Remove unsupported 'queue: max' key from concurrency in .github/workflows/nightly-sign.yml and update packaging/nightly-release-tests.py to match
- Use FLATPAK_ID (falling back to ai.storyteller.wordcraft) for runtime app_id in apps/wordcraft/src/main.rs
- Append -nightly marker to BASENAME in packaging/linux/package.sh and flatpak-bundle.sh when channel-only Nightly builds lack -nightly in VERSION
2026-11-24 14:22:00 -05:00
Dylan M. Taylorandskylartaylor ad46c883ff ci(nightly): enable supervised manual nightly runs
Port Skylar's (@skylartaylor) supervised manual nightly workflow and v3
signing policy setup from storytold/photocraft#16594 to WordCraft:

- Add .github/workflows/nightly.yml and .github/workflows/nightly-sign.yml
  pinned to craft-common-actions@605d58766e8f536564da8fc81d3676ac86816dea
  for supervised manual workflow_dispatch runs by release managers.
- Add .github/nightly-signing-policy.json adapted for storytold/wordcraft
  (repository ID 1408489772, CI workflow 380135788, SonarCloud project
  storytold_wordcraft; producer_workflow_id left null until nightly.yml
  is registered on main).
- Add docs/nightly-release-preparation.md and packaging/nightly-release-tests.py.

Co-authored-by: skylartaylor <[email protected]>
2026-11-24 14:15:18 -05:00
Dylan M. Taylor 6dd8396e20 packaging(linux): support co-installable nightly packages 2026-11-24 13:33:58 -05:00
Lucas Batista Vargas 4d7100a7f8 test(fonts): adapt installed Arabic font isolation test post-#7101 (#7734) (#7627) 2026-11-24 17:03:26 +00:00
Lucas Batista Vargas 920d9342e7 test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730) (#7630)
* test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730)

* test(chrome): drive AutoSave RTL test via ui.language and root_env
2026-11-24 17:03:20 +00:00
Lucas Batista Vargas c11504affa Ribbon: align Table Design › Table Style Options checkboxes in two columns (#7691) (#7695)
* Ribbon: align Table Style Options checkboxes in two columns (#7691)

* Ribbon: widen Table Style Options column gutter while keeping tight rows
2026-11-24 17:03:14 +00:00
Lucas Batista Vargas 604ad56f0a fix(keytips): show legacy menu key hint under slim screen bar without ribbon (#7731) (#7628) 2026-11-24 14:26:12 +00:00
Lucas Batista Vargas 852330e928 fix(chrome): return canvas focus after picking an Undo History row (#7726) (#7632) 2026-11-24 14:25:57 +00:00
Lucas Batista Vargas b5fb29b539 test(dialogs): restore RTL Page Setup oversized margin test (#7722) (#7637)
Closes #7722. Part of #7317.
2026-11-24 14:25:41 +00:00
Lucas Batista Vargas 012d0dd875 test(control_server): adapt per-connection token auth test post-#7101 (#7720) (#7631) 2026-11-24 14:25:28 +00:00
Lucas Batista Vargas 352042d41f Canvas: size Web Layout from PageView's side gutter instead of rail width (#7687) (#7701) 2026-11-24 11:50:56 +00:00
Lucas Batista Vargas 4f6cc31af6 test(dialogs): verify Customize Keyboard empty shortcuts list shows None (#7317) (#7644) 2026-11-24 11:50:50 +00:00
Lucas Batista Vargas 58e52bc962 test(dialogs): restore the_title_bar_close_box_is_the_whole_corner test (#7317) (#7638) 2026-11-24 11:50:45 +00:00
27 changed files with 1783 additions and 82 deletions
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/wordcraft",
"repository_id": 1408489772,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "wordcraft-nightly-20261124",
"repository": "storytold/wordcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135788,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_wordcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_wordcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
name: WordCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: wordcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: WordCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/wordcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: wordcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+103
View File
@@ -123,4 +123,107 @@ mod tests {
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
let options = ControlOptions { token: Some(TOKEN.to_string()), ..ControlOptions::default() };
let (rx, control) = start(&options, 0, host(), None).unwrap();
let port = control.listening.addr.port();
(port, rx, control)
}
/// Answer the next request that reaches the UI with `ok`, and return it.
fn answer(rx: &Receiver<ControlRequest>) -> ControlRequest {
let req = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
let _ = req.reply.send(serde_json::json!({"ok": true, "result": {}}));
req
}
/// One connection, several lines.
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
impl Conn {
fn open(port: u16) -> Self {
let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
Self(std::io::BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
use std::io::Write;
writeln!(self.1, "{line}").unwrap();
}
fn recv(&mut self) -> serde_json::Value {
use std::io::BufRead;
let mut r = String::new();
let n = self.0.read_line(&mut r).expect("read reply line");
assert!(n > 0, "unexpected EOF while waiting for reply");
serde_json::from_str(&r).expect("reply is valid JSON")
}
fn call(&mut self, line: &str) -> serde_json::Value {
self.send(line);
self.recv()
}
/// The server closed the connection.
fn closed(&mut self) -> bool {
use std::io::BufRead;
let mut r = String::new();
match self.0.read_line(&mut r) {
Ok(0) => true,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
_ => false,
}
}
}
/// Post-#7101 adaptation of `the_key_on_each_request` (#124, tracked under #7317 / #7720):
/// `craft::automation::server` replaced the legacy per-request `"key"` field with one-time
/// per-connection token authentication (`docs/control-protocol.md`, Token).
#[test]
fn a_connection_authenticates_once_with_the_token_and_unauthenticated_requests_are_refused() {
let (port, rx, control) = boot();
// Authenticate once per connection with `params.token`.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
// Subsequent requests on the authenticated connection carry no token and reach the UI.
c.send(r#"{"id":7,"method":"document.inspect","params":{"text":true}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": true})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(7)));
c.send(r#"{"id":8,"method":"document.inspect","params":{"text":false}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": false})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(8)));
drop(c);
// An unauthenticated connection is refused and closed without reaching the UI.
let mut unauth = Conn::open(port);
let r = unauth.call(r#"{"id":9,"method":"document.inspect"}"#);
assert_eq!(r, serde_json::json!({"id": 9, "ok": false, "error": "authentication required"}));
assert!(unauth.closed());
assert!(rx.try_recv().is_err(), "unauthenticated request must not reach the UI");
drop(unauth);
// Legacy pre-#7101 per-request `"key"` does not bypass `auth` and closes the connection.
let mut legacy = Conn::open(port);
let r = legacy.call(&format!(r#"{{"id":10,"key":"{TOKEN}","method":"document.inspect","params":{{"text":true}}}}"#));
assert_eq!(r, serde_json::json!({"id": 10, "ok": false, "error": "authentication required"}));
assert!(legacy.closed());
assert!(rx.try_recv().is_err(), "legacy per-request key must not reach the UI");
drop(legacy);
control.shut_down();
}
}
+5 -1
View File
@@ -440,10 +440,14 @@ fn main() -> eframe::Result {
None => logger.stderr_only(),
}
}
let app_id = std::env::var("FLATPAK_ID")
.ok()
.filter(|id| !id.is_empty())
.unwrap_or_else(|| "ai.storyteller.wordcraft".to_string());
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("WordCraft")
.with_app_id("ai.storyteller.wordcraft")
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
+141
View File
@@ -158,4 +158,145 @@ mod tests {
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
}
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
/// Arabic face covers it): neither installing the UI font stack for English/CJK/Arabic nor
/// triggering CJK on-demand fallback ever asks for an Arabic system font, and Arabic on-demand
/// fallback never asks for a CJK system font.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_installed_arabic_font_is_asked_for_by_arabic_alone() {
use std::path::PathBuf;
use std::sync::Mutex;
use craft::host::Wake;
use craft::i18n::Han;
use craft::ui::fonts::{FontCandidates, on_demand_registered};
struct RecordingCandidates {
scripts: Mutex<Vec<String>>,
}
impl RecordingCandidates {
fn new() -> Arc<Self> {
Arc::new(Self { scripts: Mutex::new(Vec::new()) })
}
fn scripts(&self) -> Vec<String> {
self.scripts.lock().map(|guard| guard.clone()).unwrap_or_default()
}
}
impl FontCandidates for RecordingCandidates {
fn files(&self, script: &str, han: Option<Han>) -> Vec<PathBuf> {
if let Ok(mut scripts) = self.scripts.lock() {
scripts.push(script.to_owned());
}
SystemCandidates.files(script, han)
}
fn covers(&self, data: &[u8], c: char) -> Option<u32> {
SystemCandidates.covers(data, c)
}
fn pending(&self) -> bool {
SystemCandidates.pending()
}
fn wake_when_ready(&self, wake: Wake) {
SystemCandidates.wake_when_ready(wake);
}
}
let paint = |ctx: &egui::Context, text: &str| {
for _ in 0..6 {
ctx.run_ui(egui::RawInput::default(), |ui| {
ui.label(text);
})
.drop_without_applying_deltas();
}
};
let is_cjk_script = |script: &str| matches!(script, "Hani" | "Hira" | "Kana" | "Hang" | "Bopo");
let en = Lang::EN;
let ja = crate::i18n::fixture_lang("ja", "\tHome\tホーム\n");
let ar = crate::i18n::fixture_lang("ar", "\tHome\tالرئيسية\n");
// Installing the production `ui_fonts` stack and painting Latin text never requests or
// loads an installed Arabic or CJK system font up front.
for lang in [en, ja, ar] {
let ctx = egui::Context::default();
let spy = RecordingCandidates::new();
ui_fonts(lang).on_demand(Arc::clone(&spy) as Arc<dyn FontCandidates>).install(&ctx);
assert!(on_demand_registered(&ctx).is_empty(), "{}: installing ui_fonts reads no system font eagerly", lang.code());
assert!(spy.scripts().is_empty(), "{}: installing ui_fonts requests no system font candidates", lang.code());
paint(&ctx, "Hello");
assert!(on_demand_registered(&ctx).is_empty(), "{}: Latin UI text reads no system font", lang.code());
assert!(spy.scripts().is_empty(), "{}: Latin UI text requests no system font candidates", lang.code());
}
let embedded_arabic: Vec<String> = CRAFT_FONTS.iter().filter(|f| f.has_script("Arab")).map(EmbeddedFace::name).collect();
let ar_ctx = egui::Context::default();
let ar_stack = ui_fonts(ar).install(&ar_ctx);
let en_stack = ui_fonts(en).stack();
let ja_stack = ui_fonts(ja).stack();
if !embedded_arabic.is_empty() {
assert!(
ar_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"Arabic UI leads with its embedded Arabic face"
);
assert!(
!en_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"English UI does not lead with an Arabic face"
);
assert!(
!ja_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"CJK UI does not lead with an Arabic face"
);
paint(&ar_ctx, "مرحبا");
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "embedded Arabic face draws Arabic text");
assert!(on_demand_registered(&ar_ctx).is_empty(), "no installed Arabic system font is read when an embedded Arabic face covers Arabic");
} else {
paint(&ar_ctx, "مرحبا");
let registered = on_demand_registered(&ar_ctx);
let arabic_candidates = SystemCandidates.files("Arab", None);
assert!(!registered.is_empty() || cfg!(not(any(target_os = "macos", windows))), "macOS and Windows ship an installed Arabic font");
if !registered.is_empty() {
assert_eq!(registered.len(), 1, "Arabic text registers one installed Arabic face");
assert!(arabic_candidates.contains(&registered[0].1), "registered face {:?} came from Arabic system candidates", registered[0].1);
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "installed Arabic system font draws Arabic text");
}
}
// CJK on-demand lookup through `ui_fonts` never asks for an Arabic system font (U+3400 is
// CJK Extension A, outside embedded catalog subsets, so it exercises CJK on-demand lookup
// even in builds with `CRAFT_FONTS_DIR`).
let cjk_spy = RecordingCandidates::new();
let cjk_ctx = egui::Context::default();
ui_fonts(ja).on_demand(Arc::clone(&cjk_spy) as Arc<dyn FontCandidates>).install(&cjk_ctx);
paint(&cjk_ctx, "日本語 㐀");
let cjk_scripts = cjk_spy.scripts();
assert!(!cjk_scripts.iter().any(|s| s == "Arab"), "CJK fallback never asks for an Arabic font: {cjk_scripts:?}");
if !cjk_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), '\u{3400}')) || !on_demand_registered(&cjk_ctx).is_empty() {
assert!(cjk_scripts.iter().any(|s| is_cjk_script(s)), "uncovered CJK text asks for CJK candidates: {cjk_scripts:?}");
}
// Arabic on-demand lookup when no embedded Arabic face is present asks for Arabic alone
// and never triggers a CJK system-font lookup.
let ar_spy = RecordingCandidates::new();
let ar_no_embed_ctx = egui::Context::default();
if embedded_arabic.is_empty() {
ui_fonts(ar).on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>).install(&ar_no_embed_ctx);
} else {
UiFonts::new(&I18nScripts)
.languages(&["en", "ja", "ar"])
.ui_language(ar.code())
.on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>)
.install(&ar_no_embed_ctx);
}
paint(&ar_no_embed_ctx, "مرحبا");
let ar_scripts = ar_spy.scripts();
assert!(ar_scripts.iter().any(|s| s == "Arab"), "Arabic text without an embedded Arabic face asks for Arab: {ar_scripts:?}");
assert!(!ar_scripts.iter().any(|s| is_cjk_script(s)), "Arabic fallback never asks for a CJK font: {ar_scripts:?}");
}
}
+8 -8
View File
@@ -81,6 +81,7 @@ impl WordApp {
let mode = self.screen_mode();
let dropped = self.ribbon_dropped;
let key = self.windows.window_key();
let ribbon_out = std::cell::RefCell::new(None);
let shell = AppShell::new(key)
.mode_set(ScreenModeSet::Document)
.screen_mode(Bind::given(mode))
@@ -94,12 +95,12 @@ impl WordApp {
// tabs and collapsed every one of them.
.top(Slot::new("ribbonDrop").drops().size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
if !stale(app) {
ribbon_slot(app, ui);
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
}
})
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
if !stale(app) {
ribbon_slot(app, ui);
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
}
})
// As tall as the bar: a failure's line under the message puts Install below the first line, and a slot of
@@ -132,6 +133,11 @@ impl WordApp {
self.follow_screen_mode(out.screen_mode);
}
self.ribbon_dropped = out.dropped;
// Keytips run outside the ribbon slots so legacy sequences and their hint still work when
// no ribbon shows (Focus, Full Screen View) and anchor under the slim screen bar.
let ribbon = ribbon_out.into_inner().unwrap_or_else(ribbon::no_ribbon);
let screen_bar = out.regions.slots.iter().find(|(slot, _)| *slot == "screenBar").map(|(_, rect)| *rect);
crate::keytips::show(ui, self, &ribbon, screen_bar);
out.regions
}
@@ -156,9 +162,3 @@ impl WordApp {
}
}
}
/// The ribbon, then its keytips, in a top slot: the keytips read what the ribbon recorded this pass.
fn ribbon_slot(app: &mut WordApp, ui: &mut egui::Ui) {
let out = ribbon::show(app, ui);
crate::keytips::show(ui, app, &out);
}
+29 -4
View File
@@ -156,6 +156,10 @@ pub struct CanvasState {
pub(crate) read_force_reflow: bool,
/// Web Layout's width follows the window once a drag has settled, not on every frame of it.
web_viewport: reading::Settle,
/// Side gutter the last `PageView` pass laid pages out with (`PageSpacing::side`), in screen points.
pub(crate) page_side: Option<f32>,
/// `PageView`'s side gutter changed since the last Web Layout pass, so Web Layout must reflow at once.
web_force_reflow: bool,
/// First text position on the column currently leading the reading view, captured from the last
/// pass's layout. Survives changing page sizes, even when the caret stays elsewhere.
pub(crate) read_first_visible: Option<Pos>,
@@ -405,6 +409,8 @@ impl Default for CanvasState {
nav_to_caret: false,
read_force_reflow: false,
web_viewport: Default::default(),
page_side: None,
web_force_reflow: false,
read_first_visible: None,
dragging: false,
column_drag: None,
@@ -465,16 +471,19 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
// Without an anchor (Read Mode was just entered) the view starts at the caret.
app.canvas.scroll_to_caret |= reflow_anchor.is_none();
}
app.canvas.web_force_reflow = false;
} else {
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
// Web Layout wraps to the work area (#1876).
let scale = app.session.view.zoom.clamp(0.1, 5.0) * PX_PER_PT;
// The page view keeps its side gutter (the rail width) clear on both sides of a page, so the page
// The page view keeps its side gutter (`PageSpacing::side`) clear on both sides of a page, so the page
// fits the window only when its width leaves that room.
let w = web_layout_width((full.width() - 2.0 * side).max(0.0), scale);
let changed = (app.session.view.web_width - w).abs() > 0.5;
// At once on entry or a zoom (the viewport holds still), after a window drag has settled.
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, false) {
let forced = std::mem::take(&mut app.canvas.web_force_reflow);
// At once on entry, a zoom, or a page-spacing change (the viewport holds still), after a window drag
// has settled.
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, forced) {
app.session.view.web_width = w;
// The pixel offset no longer points at the same text: keep the caret's line in view.
app.canvas.scroll_to_caret = true;
@@ -483,6 +492,7 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
}
} else {
app.canvas.web_viewport.leave();
app.canvas.web_force_reflow = false;
}
app.canvas.read_force_reflow = false;
app.canvas.read_first_visible = None;
@@ -732,7 +742,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
pub fn show(app: &mut WordApp, ui: &mut Ui) {
let full = ui.available_rect_before_wrap();
let Some(metrics) = reading_metrics::read(ui) else { return };
let layout = prepare_layout(app, full, &metrics, Env::of(ui).tokens.size.rail.width, ui.ctx());
let side = app.canvas.page_side.unwrap_or(0.0);
let layout = prepare_layout(app, full, &metrics, side, ui.ctx());
if app.session.view.read_mode {
show_reading(app, ui, &layout, full, &metrics);
} else {
@@ -871,6 +882,20 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
});
let caret = caret_after.or(caret);
app.canvas.page_keys = source.into_keys();
let side = out.spacing.side as f32;
if side.is_finite() {
let side = side.max(0.0);
if app.canvas.page_side.is_none_or(|prev| (prev - side).abs() > 0.01) {
app.canvas.page_side = Some(side);
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
app.canvas.web_force_reflow = true;
ui.ctx().request_discard("page view side gutter changed");
if !ui.ctx().will_discard() {
ui.ctx().request_repaint();
}
}
}
}
// This pass's own input changed the document under the pages it drew: run the pass again, so the frame that
// delivers a key paints its text (production laid out and painted in the one pass) rather than the next frame.
if ran && !Arc::ptr_eq(&laid_before, &app.session.layout()) {
+3 -4
View File
@@ -3,7 +3,6 @@
use craft::behavior::IconId;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{BodyCx, Props as _, Show as _, TooltipSpec};
use craft::ui::runtime::inspect;
use egui::Ui;
use serde_json::json;
@@ -11,9 +10,9 @@ use super::Screen;
use crate::WordApp;
/// Fills the screen-bar slot. Focus: a `more` button that drops the ribbon down over the page. Immersive: the
/// command search field. The bar is an inspected region, where the keytips hang their hint while no ribbon shows.
/// command search field.
pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
inspect::record(ui, crate::keytips::screen_bar_region(), |ui| match Screen::of(&app.session.view) {
match Screen::of(&app.session.view) {
Screen::Focus => {
let out = IconButton::new(IconId::new("wordcraft.more"))
.label(tl!("Show the ribbon").to_string())
@@ -27,5 +26,5 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
_ => {
super::search::show(app, ui, false);
}
});
}
}
+123
View File
@@ -103,6 +103,39 @@ fn undo_list_matches_the_session_and_undoes_up_to_the_clicked_row() {
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "the list closes");
}
/// #3040: clicking a row in the Undo History popover undoes the step and returns keyboard focus
/// to the document so typing continues immediately.
#[test]
fn undo_list_row_returns_focus_to_the_document() {
use egui::accesskit::Role;
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
assert_eq!(a.session.undo_history().len(), 1);
let mut h = harness(a);
assert!(h.state().canvas.focused(&h.ctx), "canvas starts focused");
let arrow = h.get_by_label("Undo History").rect().center();
click_at(&mut h, arrow, egui::PointerButton::Primary);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 1, "the arrow opens the Undo list");
assert!(!h.state().canvas.focused(&h.ctx), "the open Undo list holds the keyboard");
let row = h.get_by_role_and_label(Role::ListBoxOption, "Typing").rect().center();
click_at(&mut h, row, egui::PointerButton::Primary);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "picking a row closes the Undo list");
assert!(h.state().session.undo_history().is_empty(), "the step was undone");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "", "the undone text is gone");
assert!(h.state().canvas.focused(&h.ctx), "the row click returns focus to the document");
h.event(egui::Event::Text("!".into()));
crate::test_harness::frames(&mut h, 2);
assert_eq!(
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body),
"!",
"typing reaches the document immediately after picking an Undo list row"
);
}
/// #1975: the zoom percentage gains and loses digits (9% → 100% → 500%); the controls to its
/// left must not shift with it.
#[test]
@@ -437,6 +470,96 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
}
/// Finds the painted track and knob rects inside a rendered `craft::ui::choice::Switch`.
/// `Switch` sets `PARTS = false` and exposes only its `Role::Switch` node and toggled state, so
/// the thumb position is read from the unblurred filled shapes painted inside the switch rect.
fn switch_track_and_knob(shapes: &[egui::epaint::ClippedShape], switch_rect: egui::Rect) -> (egui::Rect, egui::Rect) {
fn filled_rects(shape: &egui::Shape, inside: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(children) => children.iter().for_each(|c| filled_rects(c, inside, out)),
egui::Shape::Rect(r) if r.blur_width == 0.0 && r.fill != egui::Color32::TRANSPARENT && inside.contains_rect(r.rect) => {
out.push(r.rect);
}
_ => {}
}
}
let mut rects = Vec::new();
for clipped in shapes {
filled_rects(&clipped.shape, switch_rect.expand(1.0), &mut rects);
}
let track = rects
.iter()
.copied()
.filter(|r| r.width() > r.height())
.max_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("expected painted switch track inside {switch_rect:?}: {rects:?}"));
let knob = rects
.iter()
.copied()
.filter(|r| track.contains_rect(*r) && r.width() < track.width())
.max_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("expected painted switch knob inside track {track:?}: {rects:?}"));
(track, knob)
}
/// The AutoSave switch renders its knob on the right when on and on the left when off in a
/// left-to-right interface, and mirrors through `WordApp::root_env()` for an Arabic interface.
#[test]
fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
use craft::i18n::Direction;
use egui::accesskit::{Role, Toggled};
struct ResetLang;
impl Drop for ResetLang {
fn drop(&mut self) {
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
let _reset = ResetLang;
let mut a = new_app();
a.ui.animations = crate::theme::Animations::Off;
a.ui.language = "en".into();
// Mark the document as saved here without touching disk (`session.dirty` stays false).
let path = std::path::PathBuf::from("draft.docx");
a.session.path = Some(path.clone());
a.autosave_path = Some(path);
let mut h = harness(a);
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
let mut measure = |lang: crate::i18n::Lang, on: bool| -> (egui::Rect, egui::Rect) {
h.state_mut().run("ui.language", json!({"value": lang.code()})).unwrap();
h.state_mut().run("file.autosave", json!({"value": on})).unwrap();
let want_dir = if lang.rtl() { Direction::Rtl } else { Direction::Ltr };
assert_eq!(h.state().root_env().direction, want_dir, "root_env supplies direction for {}", lang.code());
assert_eq!(h.state().autosaves(), on);
crate::test_harness::frames(&mut h, 4);
let label = crate::i18n::tr(lang, "AutoSave");
let node = h.get_by_role_and_label(Role::Switch, label);
assert_eq!(node.accesskit_node().toggled(), Some(if on { Toggled::True } else { Toggled::False }));
switch_track_and_knob(&h.output().shapes, node.rect())
};
let (ltr_on_track, ltr_on_knob) = measure(crate::i18n::Lang::EN, true);
let (ltr_off_track, ltr_off_knob) = measure(crate::i18n::Lang::EN, false);
assert!(ltr_on_knob.center().x > ltr_on_track.center().x, "left to right, on: knob sits right ({ltr_on_knob:?} in {ltr_on_track:?})");
assert!(ltr_off_knob.center().x < ltr_off_track.center().x, "left to right, off: knob sits left ({ltr_off_knob:?} in {ltr_off_track:?})");
let Some(ar) = crate::i18n::Lang::from_code("ar") else {
eprintln!("skipped RTL check: built without the craft-i18n Arabic catalog (set CRAFT_I18N_DIR to a checkout)");
return;
};
let (rtl_on_track, rtl_on_knob) = measure(ar, true);
let (rtl_off_track, rtl_off_knob) = measure(ar, false);
assert!(rtl_on_knob.center().x < rtl_on_track.center().x, "right to left, on: knob sits left ({rtl_on_knob:?} in {rtl_on_track:?})");
assert!(rtl_off_knob.center().x > rtl_off_track.center().x, "right to left, off: knob sits right ({rtl_off_knob:?} in {rtl_off_track:?})");
assert!(rtl_on_track.center().x > ltr_on_track.center().x, "right to left mirrors the AutoSave switch toward the start (right) edge");
assert!(((ltr_on_knob.center().x - ltr_on_track.min.x) - (rtl_on_track.max.x - rtl_on_knob.center().x)).abs() <= 0.5);
assert!(((ltr_off_knob.center().x - ltr_off_track.min.x) - (rtl_off_track.max.x - rtl_off_knob.center().x)).abs() <= 0.5);
}
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
+5
View File
@@ -200,6 +200,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
if let Some(count) = picked {
let _ = app.run("edit.undoTo", json!({"count": count}));
// Picking a row closes the Undo History popover on its foreground layer; return keyboard
// focus to the document both now and after the pass's overlay-close focus hook (#3040).
app.canvas.focus_page(ui.ctx());
app.canvas.focus_page_after_pass();
ui.ctx().request_repaint();
}
out.response.rect
}
@@ -147,10 +147,14 @@ pub(crate) fn open(app: &mut WordApp, _name: &str, _params: &Value, parent: Opti
#[cfg(test)]
mod tests {
use craft::keymap::Binding;
use craft::keymap::{Binding, CommandRef};
use craft::ui::dialog::dialog_id;
use egui::accesskit::Role;
use egui_kittest::kittest::{By, NodeT, Queryable};
use serde_json::json;
use wordcraft_engine::Session;
use super::KEY;
use crate::{Services, WordApp};
fn app() -> WordApp {
@@ -181,4 +185,66 @@ mod tests {
assert_eq!(chords(&b, "format.bold"), Some(Vec::new()));
assert_eq!(chords(&b, "format.italic"), Some(italic));
}
/// #1905: a command with no shortcuts shows `None` in the Current shortcuts list, whereas a
/// command with a built-in shortcut shows its binding instead of `None`.
#[test]
fn keys_list_without_shortcuts_says_none() {
let mut a = app();
super::open(&mut a, KEY, &json!({}), None).expect("dialog opens");
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
h.run_steps(2);
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board installs a keymap");
let unbound_id = h
.state()
.session
.registry
.all()
.iter()
.find(|spec| {
let cmd = CommandRef::new(spec.id);
keymap.bindable(&cmd).is_some() && keymap.bindings(&cmd).is_empty()
})
.map(|spec| spec.id.to_string())
.expect("a bindable command with no built-in shortcut");
assert!(!keymap.bindings(&CommandRef::new("format.bold")).is_empty(), "format.bold has a built-in shortcut");
let dlg_id = dialog_id(KEY);
let ctx = h.ctx.clone();
let select = |h: &mut egui_kittest::Harness<'_, WordApp>, id: &str| {
h.state_mut().dialog_host.set_json_field(&ctx, dlg_id, "command", json!(id)).expect("command field accepts id");
h.run_steps(3);
let selected = h
.state()
.dialog_host
.open_dialogs()
.into_iter()
.find(|d| d.id == dlg_id)
.and_then(|d| d.fields)
.and_then(|fields| fields.get("command").and_then(|v| v.as_str()).map(str::to_owned));
assert_eq!(selected.as_deref(), Some(id), "dialog selected {id}");
};
let keys_list_labels = |h: &egui_kittest::Harness<'_, WordApp>| -> Vec<String> {
let list = h.get_by_role_and_label(Role::List, "Current shortcuts:");
let list_id = list.accesskit_node().id();
let rect = list.rect();
h.query_all(By::new())
.filter(|n| n.accesskit_node().id() != list_id && !n.accesskit_node().is_hidden() && n.accesskit_node().bounding_box().is_some())
.filter(|n| rect.contains_rect(n.rect()))
.filter_map(|n| n.accesskit_node().label())
.collect()
};
// Positive contrast: a bound command lists its shortcut and does not show the empty `None` placeholder.
select(&mut h, "format.bold");
let bound_labels = keys_list_labels(&h);
assert!(!bound_labels.is_empty(), "bound command lists its shortcut");
assert!(!bound_labels.iter().any(|t| t == "None"), "bound command keys list does not say None: {bound_labels:?}");
// Target behavior: an unbound command shows `None` inside the Current shortcuts list.
select(&mut h, &unbound_id);
let unbound_labels = keys_list_labels(&h);
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
}
}
+125
View File
@@ -950,6 +950,83 @@ fn opened_paper(h: &mut egui_kittest::Harness<'_, WordApp>) -> (f32, f32) {
paper
}
/// #1433: in a right-to-left interface, typing a number wider than the field's column into a
/// margin spin button keeps the dialog the same width; clicking the visible end of the blurred
/// field enters editing again, and entering a normal value restores the field.
#[test]
fn page_setup_rtl_large_margin_can_be_edited_again_after_blur() {
use egui::accesskit::Role;
let mut app = app_with("Page");
app.run("ui.dialog", json!({"name": "pageSetup"})).unwrap();
let ar = crate::i18n::fixture_lang("ar", "\tMargins\tMargins\n");
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
move |ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
// Draw the actual dialog in a fixture language even without embedded catalogs.
crate::i18n::apply_language(ar);
ctx.global_style_mut(|s| s.right_to_left = true);
assert!(crate::i18n::current().rtl() && ctx.global_style().right_to_left);
craft::ui::runtime::env::with_env(ui, |o| o.direction = Some(craft::i18n::Direction::Rtl), |ui| app.ui(ui));
ctx.global_style_mut(|s| s.right_to_left = false);
crate::i18n::apply_language(crate::i18n::Lang::EN);
},
app,
);
h.run_steps(4);
let initial = h.get_by_role_and_label(Role::SpinButton, "Bottom").rect();
assert!(h.get_by_role_and_label(Role::SpinButton, "Top").rect().center().x > initial.center().x, "the form is mirrored");
let window = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::Dialog, "Page Setup").rect();
let before = window(&h).width();
let id = id_of(h.state(), "pageSetup");
let initial_bottom = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
assert!(initial_bottom < craft::pages::setup::MAX_PAGE_SIDE, "initial margin starts below the upper bound: {initial_bottom}");
h.get_by_role_and_label(Role::SpinButton, "Bottom").click();
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Paste(format!("1{}", "0".repeat(36))));
h.run_steps(3);
let id = id_of(h.state(), "pageSetup");
let value = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
assert!(
value > initial_bottom && (value - craft::pages::setup::MAX_PAGE_SIDE).abs() < 1e-3,
"oversized margin paste should be accepted and clamped to MAX_PAGE_SIDE: got {value}"
);
// While the 37-digit text is in the field, the dialog does not blow up to the typed text width.
assert!(window(&h).width() <= before + 15.0);
h.key_press(egui::Key::Tab);
h.run_steps(3);
let id = id_of(h.state(), "pageSetup");
assert_eq!(h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom, value);
let field = h.get_by_role_and_label(Role::SpinButton, "Bottom");
assert!(!field.is_focused());
let wide = field.rect();
let visible = wide.intersect(initial).intersect(window(&h));
assert!(visible.is_positive());
// The inline notice "Margins do not fit" may add a few points, but the dialog does not blow up to the typed text width.
assert!(window(&h).width() <= before + 15.0);
// The AccessKit bounds include clipped text: click the visible part, not their centre.
let pos = visible.center();
h.event(egui::Event::PointerMoved(pos));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
}
h.run_steps(3);
assert!(h.get_by_role_and_label(Role::SpinButton, "Bottom").is_focused(), "the visible field enters editing");
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Paste("2".into()));
h.run_steps(3);
h.key_press(egui::Key::Tab);
h.run_steps(3);
let id = id_of(h.state(), "pageSetup");
let bottom = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
let unit = crate::options::unit_kind(h.state().session.units());
let expected =
unit.to_pixels(2.0, 0.0, craft::ui::runtime::env::UnitKind::POINTS_PER_INCH, craft::ui::runtime::env::UnitKind::POINTS_PER_INCH).unwrap();
assert!((bottom - expected).abs() < 1e-3, "the field accepts a normal value again: got {bottom}, expected {expected}");
assert!(window(&h).width() <= before + 2.0);
}
/// #1433: Page Setup's Paper size shows the named size the section has, in either
/// orientation, and Custom size (None) for anything else.
#[test]
@@ -1674,6 +1751,54 @@ fn word_count_shows_label_and_count_on_a_line_over_close_and_cancel() {
assert!(!is_open(h.state(), "wordCount"), "Cancel closes Word Count");
}
/// #1885: the close control is at the title bar's right end; a click in the close box
/// closes the dialog; one just under the title bar leaves it open; a drag that starts on the box
/// doesn't move the dialog.
#[test]
fn the_title_bar_close_box_is_the_whole_corner() {
use egui::accesskit::Role;
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, from: egui::Pos2, to: egui::Pos2) {
let button =
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
h.event(egui::Event::PointerMoved(from));
h.step();
h.event(button(from, true));
h.step();
if to != from {
h.event(egui::Event::PointerMoved(to));
h.step();
}
h.event(button(to, false));
for _ in 0..4 {
h.step();
}
}
let mut app = app_with("Some text");
super::open(&mut app, "wordCount", &json!({})).expect("word count opens");
let mut h = app_harness(app);
h.run_steps(4);
assert!(is_open(h.state(), "wordCount"), "dialog is open");
let before = h.get_by_role_and_label(Role::Dialog, "Word Count").rect();
let closes: Vec<_> = h.query_all_by_role_and_label(Role::Button, "Close").filter(|n| !n.accesskit_node().is_hidden()).collect();
let close_box = closes.into_iter().min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y)).expect("title bar close");
let bx = close_box.rect();
assert!((bx.top() - before.top()).abs() <= 10.0, "box {bx:?} is in the title bar area of {before:?}");
assert!(
bx.right() <= before.right() && before.right() - bx.right() <= 10.0 && bx.left() > before.center().x,
"close button sits at the right: {bx:?} in {before:?}"
);
let under = egui::pos2(bx.center().x, bx.bottom() + 4.0);
press(&mut h, under, under);
assert!(is_open(h.state(), "wordCount"), "a click under the title bar keeps the dialog");
let at = bx.center();
press(&mut h, at, at + egui::vec2(-150.0, 90.0));
assert!(is_open(h.state(), "wordCount"), "a drag from the box isn't a click");
let after = h.get_by_role_and_label(Role::Dialog, "Word Count").rect();
assert!((after.min - before.min).length() <= 1.0, "the box isn't a drag handle: {before:?} -> {after:?}");
press(&mut h, at, at);
assert!(!is_open(h.state(), "wordCount"), "a click in the box closes the dialog");
}
// ---------------------------------------------------------------- Font layout
/// The Font dialog stands as the old one did: the Effects check boxes two to a line (Bold beside Italic, Underline
+8 -12
View File
@@ -5,6 +5,7 @@
use std::sync::Arc;
use craft::behavior::overlay::MinWidth;
use craft::keymap::CommandRef;
use craft::menu::{KeytipControl, Keytips, RibbonOutput};
use craft::ui::contract::Bind;
@@ -33,12 +34,6 @@ pub(crate) fn backstage_region() -> egui::Id {
egui::Id::unique("wc_keytips_backstage_region")
}
/// The key of the inspected region the screen bar (Focus, Full Screen View) records; the legacy hint hangs from
/// its first element when no ribbon shows.
pub(crate) fn screen_bar_region() -> egui::Id {
egui::Id::unique("wc_keytips_screen_bar_region")
}
/// Word's tab letters, as Word for Windows shows them after Alt (File F, Design G, References S,
/// Review R, View W, Help Y). File opens the Backstage.
const TAB_LETTERS: [(&str, &str); 11] = [
@@ -417,8 +412,8 @@ fn backstage_rows() -> Vec<Row> {
.collect()
}
/// Shows the keytips after the ribbon and the regions they place badges on, and acts on what the keys chose.
pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>) {
/// Shows the keytips after the shell and the regions they place badges on, and acts on what the keys chose.
pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>, screen_bar: Option<Rect>) {
let ctx = ui.ctx().clone();
// Alt during an object drag is part of the drag (Alt moves an object freely), not a keytip tap.
// PLAN: `CanvasState::object_gesture` is canvas-w9's (cv.A10).
@@ -471,7 +466,6 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
}
if let Some(pending) = &out.pending {
// With no ribbon showing (Focus, Full Screen View) the hint hangs under the screen bar.
let screen_bar = inspect::recorded(&ctx, screen_bar_region()).and_then(|r| r.rect_in(&ctx, 0, ui.layer_id()));
if let Some(anchor) = ribbon.tabs.or(screen_bar) {
legacy_hint(ui, pending, anchor);
}
@@ -483,9 +477,11 @@ fn legacy_hint(ui: &mut Ui, pending: &str, anchor: Rect) {
let keys: Vec<String> = pending.chars().map(String::from).collect();
let text = crate::i18n::fmt(tl!("Old menu keys: Alt, {keys}. Keep typing, or press Esc to cancel."), &[("keys", &keys.join(", "))]);
let mut open = true;
Popover::new(tl!("Old menu keys"), Bind::bound(&mut open)).overlay(|overlay| overlay.anchor(Anchor::Rect(anchor))).show(ui, |ui, _| {
Text::new(text.clone()).show(ui);
});
Popover::new(tl!("Old menu keys"), Bind::bound(&mut open))
.overlay(|overlay| overlay.anchor(Anchor::Rect(anchor)).min_width(MinWidth::None))
.show(ui, |ui, _| {
Text::new(text.clone()).show(ui);
});
}
#[cfg(test)]
+82
View File
@@ -96,6 +96,88 @@ fn legacy_menu_keys_stay_off_the_ribbon_letters_and_all_resolve() {
}
}
/// #1697 review: with no ribbon showing (Focus, Full Screen View) no tab rects are recorded,
/// so the legacy hint hangs under the slim screen bar at the top of the window instead of not
/// showing; with the ribbon showing (normal window or dropped ribbon in Focus) it hangs under
/// the tab row.
#[test]
fn the_legacy_hint_hangs_under_the_slim_bar_without_a_ribbon() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable as _;
if cfg!(target_os = "macos") {
return;
}
let trigger_legacy_v = |h: &mut egui_kittest::Harness<'static, WordApp>| {
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(h);
h.input_mut().events.extend([key_event(egui::Key::V, true, egui::Modifiers::NONE), egui::Event::Text("v".into())]);
crate::test_harness::frames(h, 2);
};
let cancel = |h: &mut egui_kittest::Harness<'static, WordApp>| {
h.input_mut().events.push(key_event(egui::Key::Escape, true, egui::Modifiers::NONE));
crate::test_harness::frames(h, 2);
};
let mut h = harness(app());
let home_tab = h.get_by_label("Home").rect();
trigger_legacy_v(&mut h);
assert!(h.state().keytips_active, "F10, V enters legacy keytip wait with the ribbon showing");
assert!(h.query_by_label("Old menu keys: Alt, V. Keep typing, or press Esc to cancel.").is_some(), "hint displays pending Alt, V sequence");
let ribbon_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(ribbon_hint.top() >= home_tab.bottom() - 1.0, "legacy hint {ribbon_hint:?} hangs under the ribbon tab row {home_tab:?}");
cancel(&mut h);
assert!(!h.state().keytips_active, "Escape ends legacy keytips");
assert!(h.query_by_role_and_label(Role::Dialog, "Old menu keys").is_none(), "hint closes on Escape");
// Focus hides the ribbon and shows the slim screen bar at the top.
h.state_mut().run("view.focus", serde_json::json!({})).unwrap();
crate::test_harness::frames(&mut h, 3);
assert!(h.query_by_label("Insert").is_none(), "Focus hides the ribbon");
let focus_bar = h.get_by_label("Show the ribbon").rect();
trigger_legacy_v(&mut h);
assert!(h.state().keytips_active, "F10, V activates legacy keytips in Focus mode");
let focus_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(
focus_hint.top() >= focus_bar.bottom() - 1.0 && focus_hint.top() < ribbon_hint.top(),
"Focus legacy hint {focus_hint:?} hangs under the slim screen bar {focus_bar:?} (above ribbon hint {ribbon_hint:?})"
);
assert!(focus_hint.width() < 720.0, "Focus hint {focus_hint:?} sizes to its content rather than stretching across the screen bar");
cancel(&mut h);
assert!(!h.state().keytips_active, "Escape ends legacy keytips in Focus");
assert!(h.state().session.view.focus_mode, "Escape cancelling legacy keytips keeps Focus active");
// When Focus drops the ribbon down, the tab row wins over the screen bar.
h.state_mut().run("ui.focusRibbon", serde_json::json!({"value": true})).unwrap();
crate::test_harness::frames(&mut h, 3);
let dropped_tab = h.get_by_label("Home").rect();
trigger_legacy_v(&mut h);
let dropped_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(
dropped_hint.top() >= dropped_tab.bottom() - 1.0 && dropped_hint.top() > focus_hint.top(),
"dropped-ribbon hint {dropped_hint:?} hangs under the dropped tab row {dropped_tab:?}"
);
cancel(&mut h);
// Full Screen View hides the ribbon and shows the slim screen bar with Search.
h.state_mut().run("view.focus", serde_json::json!({})).unwrap();
h.state_mut().run("view.fullScreenView", serde_json::json!({})).unwrap();
crate::test_harness::frames(&mut h, 3);
assert!(h.query_by_label("Insert").is_none(), "Full Screen View hides the ribbon");
let search_bar = h.get_by_label("Search commands and help").rect();
trigger_legacy_v(&mut h);
assert!(h.state().keytips_active, "F10, V activates legacy keytips in Full Screen View");
let fs_hint = h.get_by_role_and_label(Role::Dialog, "Old menu keys").rect();
assert!(
fs_hint.top() >= search_bar.bottom() - 1.0 && fs_hint.top() < ribbon_hint.top(),
"Full Screen View legacy hint {fs_hint:?} hangs under the slim screen bar {search_bar:?} (above ribbon hint {ribbon_hint:?})"
);
assert!(fs_hint.width() < 720.0, "Full Screen View hint {fs_hint:?} sizes to its content rather than stretching across the screen bar");
h.input_mut().events.extend([key_event(egui::Key::U, true, egui::Modifiers::NONE), egui::Event::Text("u".into())]);
crate::test_harness::frames(&mut h, 3);
assert!(!h.state().session.view.full_screen_view, "Alt/F10, V, U leaves Full Screen View");
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).is_empty(), "no letter typed into the document");
}
#[test]
fn qat_keytips_follow_custom_order_and_skip_disabled_commands() {
let mut a = app();
+1 -1
View File
@@ -68,7 +68,7 @@ pub use tabs::{
use view::{outlining, view};
/// What a pass with no ribbon reports.
fn no_ribbon() -> RibbonOutput<String> {
pub(crate) fn no_ribbon() -> RibbonOutput<String> {
// PLAN: assumed `RibbonOutput::tab_ids` (S-L361) has a `Default` value; the field replaces `menu`.
RibbonOutput { shown: None, picked: None, controls: None, tabs: None, tab_ids: Default::default() }
}
+24 -15
View File
@@ -1,10 +1,11 @@
use craft::behavior::IconId;
use craft::behavior::{ColumnWidth, IconId};
use craft::keymap::CommandRef;
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
use craft::ui::buttons::{Arrangement, Button, IconButton, ToggleButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout::{GridFit, empty_cell};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::menu::MenuItem;
use craft::ui::text::NumberField;
@@ -17,25 +18,33 @@ use crate::undo_marks::apply_edits;
/// The row height and column width a Cell Size field accepts, in points (0.02 to 22 inches).
const CELL_SIZE_RANGE: std::ops::RangeInclusive<f64> = 1.44..=1584.0;
/// Two checkbox columns separated by two empty gutter cells: `Grid::gap` sets both axes, so the
/// empty gutter widens the column gap to `3 * Gap::Tight` (at least `Gap::Stack`) while keeping
/// rows `Gap::Tight` apart inside the ribbon group.
const TABLE_STYLE_OPTION_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content; 4];
pub(super) fn table_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let look = app.session.sel.focus.path.cell().and_then(|(tp, _, _)| app.session.doc.table(app.session.sel.focus.story, &tp).map(|t| t.props.look));
if let Some(l) = look {
// Three rows of two, so Tab runs Header Row, First Column, Total Row, Last Column, Banded Rows, Banded Columns.
// Row-major pairs, so Tab runs Header Row, First Column, Total Row, Last Column, Banded Rows, Banded Columns.
let options = [
[("Header Row", "headerRow", l.header_row), ("First Column", "firstColumn", l.first_column)],
[("Total Row", "totalRow", l.total_row), ("Last Column", "lastColumn", l.last_column)],
[("Banded Rows", "bandedRows", l.banded_rows), ("Banded Columns", "bandedColumns", l.banded_columns)],
("Header Row", "headerRow", l.header_row),
("First Column", "firstColumn", l.first_column),
("Total Row", "totalRow", l.total_row),
("Last Column", "lastColumn", l.last_column),
("Banded Rows", "bandedRows", l.banded_rows),
("Banded Columns", "bandedColumns", l.banded_columns),
];
row.group(RibbonGroup::new("tableStyleOptions", tl!("Table Style Options").to_string(), IconId::new("tableStyleOptions").into()), |ui| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for line in options {
Row::new().show(ui, |ui, _| {
for (label, key, value) in line {
let out = Checkbox::new(Bind::given(value)).label(tl!(label).to_string()).show(ui);
apply_edits(app, out.events, |app, v| {
let _ = app.run("table.look", json!({ key: v }));
});
}
Grid::new(&TABLE_STYLE_OPTION_COLUMNS).fit(GridFit::Fixed).gap(Gap::Tight).show(ui, |ui, _| {
for (index, (label, key, value)) in options.into_iter().enumerate() {
if index % 2 == 1 {
empty_cell(ui);
empty_cell(ui);
}
let out = Checkbox::new(Bind::given(value)).label(tl!(label).to_string()).show(ui);
apply_edits(app, out.events, |app, v| {
let _ = app.run("table.look", json!({ key: v }));
});
}
});
+63
View File
@@ -994,3 +994,66 @@ fn decorative_text_dropdown_renders_compact_wordart_tiles() {
rect.height()
);
}
/// #7691: Table Design › Table Style Options aligns its six checkboxes in two columns with a gap
/// between them and keeps all three rows above the group caption.
#[test]
fn table_style_options_align_in_two_columns() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let h = tab_harness(app, "Table Design");
let rect = |label: &str| h.get_by_role_and_label(Role::CheckBox, label).rect();
let header = rect("Header Row");
let first_col = rect("First Column");
let total = rect("Total Row");
let last_col = rect("Last Column");
let banded = rect("Banded Rows");
let banded_col = rect("Banded Columns");
// Left column checkboxes share one left edge, and right column checkboxes share another.
assert!(
(header.left() - total.left()).abs() < 0.5 && (header.left() - banded.left()).abs() < 0.5,
"left column misaligned: {header:?}, {total:?}, {banded:?}"
);
assert!(
(first_col.left() - last_col.left()).abs() < 0.5 && (first_col.left() - banded_col.left()).abs() < 0.5,
"right column misaligned: {first_col:?}, {last_col:?}, {banded_col:?}"
);
// Each row's pair shares the same top edge and stacks vertically with tight spacing.
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let tight_gap = env.tokens.space.gap.tight;
let min_col_gap = env.tokens.space.gap.stack;
assert!((header.top() - first_col.top()).abs() < 0.5, "row 1 misaligned: {header:?}, {first_col:?}");
assert!((total.top() - last_col.top()).abs() < 0.5, "row 2 misaligned: {total:?}, {last_col:?}");
assert!((banded.top() - banded_col.top()).abs() < 0.5, "row 3 misaligned: {banded:?}, {banded_col:?}");
assert!(header.bottom() <= total.top() && total.bottom() <= banded.top(), "rows overlap: {header:?}, {total:?}, {banded:?}");
let row_gap_1 = total.top() - header.bottom();
let row_gap_2 = banded.top() - total.bottom();
assert!(
(row_gap_1 - tight_gap).abs() <= 0.5 && (row_gap_2 - tight_gap).abs() <= 0.5,
"rows should remain Gap::Tight ({tight_gap} pt) apart, got {row_gap_1} and {row_gap_2}"
);
// A horizontal gap at least `space.gap.stack` separates the widest left-column label from the second column.
let text_rect = |label: &str| {
h.output()
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == label => Some(egui::Rect::from_min_size(t.pos, t.galley.size())),
_ => None,
})
.unwrap_or_else(|| panic!("painted text for {label:?}"))
};
let left_label_max_right =
["Header Row", "Total Row", "Banded Rows"].into_iter().map(|label| text_rect(label).right()).fold(f32::NEG_INFINITY, f32::max);
let col_gap = first_col.left() - left_label_max_right;
assert!(
col_gap >= min_col_gap,
"column gap between widest left label and right column too narrow: got {col_gap:.2} pt, expected >= {min_col_gap:.2} pt (left_label_max_right={left_label_max_right}, first_col={first_col:?})"
);
// All three rows stay above the group's caption.
let caption = text_rect("Table Style Options");
assert!(banded.bottom() <= caption.top(), "checkboxes collide with group caption: {banded:?} vs {caption:?}");
}
+24 -5
View File
@@ -850,11 +850,13 @@ fn web_layout_fills_the_window_width() {
frame(&mut a, 1400.0, tick);
assert_eq!(a.session.view.web_width, wide, "no change without a resize");
let page = first_page(&a).unwrap();
// The page view keeps a side gutter clear (the rail width, S-L: the framework's page spacing); the page fills the
// rest of the window, so it neither overflows to the right nor leaves more than the gutter on the left.
let gutter = 40.0; // the `size.rail.width` token the page view keeps clear
assert!(page.left() <= gutter + 4.0, "page starts at the left gutter: {page:?}");
assert!(page.right() <= 1400.0 - gutter + 4.0, "page ends before the right gutter: {page:?}");
// The page view keeps its `PageSpacing::side` gutter clear on both sides; the page fills the rest of the window,
// so it uses the full room up to the PageView gutter rather than the wider rail width, without overflowing.
let gutter = a.canvas.page_side.expect("page view records its side gutter");
let rail = craft::ui::runtime::env::Env::of_root(&ctx).tokens.size.rail.width;
assert!(gutter < rail, "Productivity PageView gutter ({gutter}) is narrower than the rail width ({rail})");
assert!((page.left() - gutter).abs() <= 4.0, "page starts at the left gutter ({gutter}): {page:?}");
assert!(page.right() >= 1400.0 - gutter - 4.0 && page.right() <= 1400.0 - gutter + 4.0, "page fills to the right gutter ({gutter}): {page:?}");
// A window drag: the width holds while the size keeps changing, then follows once it settles.
for w in [1300.0, 1100.0, 900.0, 700.0, 500.0] {
frame(&mut a, w, tick);
@@ -887,6 +889,23 @@ fn web_layout_fills_the_window_width() {
frame(&mut a, 1400.0, tick);
}
assert_eq!(lines(&mut a), print_lines, "Print Layout is unchanged");
// Entering Web Layout before any prior PageView pass still settles to PageView's side gutter.
let fresh_ctx = crate::test_harness::context();
let mut fresh = app();
fresh.run("view.webLayout", json!({})).unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 740.0));
for step in 1..=2 {
let input = egui::RawInput { events: vec![], time: Some(step as f64 * tick), screen_rect: Some(screen), ..Default::default() };
crate::test_harness::pass(&fresh_ctx, &mut fresh, input);
}
let fresh_gutter = fresh.canvas.page_side.expect("page view records its side gutter on first Web Layout pass");
let fresh_page = first_page(&fresh).unwrap();
assert!((fresh_page.left() - fresh_gutter).abs() <= 4.0, "fresh Web Layout starts at the left gutter ({fresh_gutter}): {fresh_page:?}");
assert!(
fresh_page.right() >= 1400.0 - fresh_gutter - 4.0 && fresh_page.right() <= 1400.0 - fresh_gutter + 4.0,
"fresh Web Layout fills to the right gutter ({fresh_gutter}): {fresh_page:?}"
);
}
/// #688: dragging a selection past the viewport's edge scrolls the view toward the pointer, and the
+93
View File
@@ -0,0 +1,93 @@
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the
signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed
manual actors dispatches them. There is no schedule yet. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy.
Once `nightly.yml` lands on `main`, populate `producer_workflow_id` before promoting the policy to
`release` by reading:
```bash
gh api repos/storytold/wordcraft/actions/workflows/nightly.yml --jq .id
```
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
permissions are for its isolated attester; its compiler narrows to contents and Actions read
only, with no OIDC, attestation write, release environment or platform signing secrets.
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
lineage compares and an issue reread at the end of candidate admission) on top of
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed
source availability, not provider, queue, native signing or crypto qualification.
Existing stable workflows are unchanged.
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
producer run ID and attempt, by a listed manual actor.
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes.
**Admission timing.** The candidate check reads the newest CI run on the candidate commit and
main's latest finished Sonar analysis, so pick a quiet main, wait for its CI and SonarCloud analysis
to finish green, then dispatch the producer and, once it succeeds, the signer, before another main
push lands a newer analysis.
**Platform rows.** The producer caller lists
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer
run builds every listed platform for one all-or-nothing release (one failed or skipped platform stops
that night's release), and the release-ref signer admits platforms only from the protected policy, so
there is no separate Linux or macOS caller job and the signer caller has no platform input.
## Installed policy values and their sources
Read on 2026-11-24; re-read anything that may have moved (and fill in `producer_workflow_id` after
`nightly.yml` lands on `main`) before the policy is promoted to `release`.
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1408489772` | `gh api repos/storytold/wordcraft --jq .id` |
| `producer_workflow_id` | `null` (pending `main` registration) | Read via `gh api repos/storytold/wordcraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` reaches `main` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin |
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | Storytold stable signing identities (Windows Authenticode subject, Linux OpenPGP fingerprint, macOS Apple Team ID `DJ6XS33FX8`) |
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135788`), `gate / gate (ubuntu-24.04)` | Workflow list API; always-run main push gate job |
| `candidate_policy.sonar` | `storytold` / `storytold_wordcraft`, app `12526` | `sonar-project.properties` |
| Sonar conditions | `new_security_rating` accepted (max 5); the other five required | Standard Storytold SonarCloud quality gate |
| Sonar `issue_types` / `debt` | `VULNERABILITY`; `[]` | Refresh from SonarCloud before promoting policy to `release` |
The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether
an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh
those values in the same reviewed change that promotes the policy to `release`.
## Ownership and interface
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`WordCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
may be passed or inherited.
- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch,
and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual
branch, including same-name tags. Its constant whole-run concurrency (`wordcraft-nightly-release`,
`queue: max`, `cancel-in-progress: false`) is distinct from stable. The caller itself passes no
credentials; only the shared callee's sign jobs bind the `release` environment.
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable commit**;
the defining workflow SHA and tooling input must match.
- `packaging/windows/sign.ps1 -Required` is the app-owned Windows adapter, invoked only from the
immutable release execution SHA checkout.
## Local regression checks
`python3 packaging/nightly-release-tests.py` verifies:
- Both callers share one full 40-char commit pin in `uses` and `tooling-revision`.
- Both callers keep their exact context guards (reading all continuation lines), have no cache
actions/options or secrets, and register no schedule.
- `nightly-sign.yml` keeps its literal `wordcraft-nightly-release` concurrency group, `queue: max`,
and `cancel-in-progress: false`.
- `manual-actors` in `nightly.yml` and `manual_actors` in `.github/nightly-signing-policy.json` are
identical and equal to the reviewed release managers list, with `automatic_signer_actors` empty.
- `.github/nightly-signing-policy.json` matches the `craft-nightly-release-policy/v3` schema,
repository identity, platform trust anchors, CI workflow trigger, and `sonar-project.properties`.
+41 -8
View File
@@ -17,6 +17,12 @@ set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.wordcraft
FLATPAK_ID="$APP_ID"
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
FLATPAK_BRANCH=stable
if [[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
FLATPAK_ID="$APP_ID.nightly"
fi
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
TEST=1
@@ -38,7 +44,11 @@ case "$ARCH" in
aarch64 | arm64) ARCH=aarch64 ;;
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
BASENAME="wordcraft-$VERSION-linux-$ARCH"
BASENAME_VERSION="$VERSION"
if [[ "$FLATPAK_ID" != "$APP_ID" && "$BASENAME_VERSION" != *-nightly* ]]; then
BASENAME_VERSION="$BASENAME_VERSION-nightly"
fi
BASENAME="wordcraft-$BASENAME_VERSION-linux-$ARCH"
TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}"
[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; }
for tool in flatpak flatpak-builder; do
@@ -52,29 +62,52 @@ rm -rf "$WORK"
mkdir -p "$WORK/stage"
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
[[ -x "$WORK/stage/bin/wordcraft" ]] || { echo "error: $TARBALL has no bin/wordcraft" >&2; exit 1; }
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
-e '/^MimeType=/d' \
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
-e "s|<name>WordCraft</name>|<name>WordCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml"
rm -rf "$WORK/stage/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
sed -e "s|ai\.storyteller\.wordcraft|$FLATPAK_ID|g" \
"$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
else
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml"
fi
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
OUT="$DIST/$BASENAME.flatpak"
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote $OUT"
if [[ "$OCI" = 1 ]]; then
OUT_OCI="$DIST/$BASENAME-oci"
rm -rf "$OUT_OCI"
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote OCI layout to $OUT_OCI"
fi
if [[ "$TEST" = 1 ]]; then
flatpak install --user -y --noninteractive --reinstall "$OUT"
flatpak info --user "$APP_ID"
flatpak run --command=wordcraft-cli "$APP_ID" --version
flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps'
flatpak info --user "$FLATPAK_ID"
flatpak run --command=wordcraft-cli "$FLATPAK_ID" --version
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
fi
echo "==> done"
ls -lh "$OUT"
+16 -13
View File
@@ -3,7 +3,7 @@
# exports VERSION and NFPM_ARCH.
#
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: wordcraft
name: ${NFPM_NAME}
arch: ${NFPM_ARCH}
platform: linux
version: ${VERSION}
@@ -67,26 +67,29 @@ overrides:
- espeak-ng
contents:
- src: ${STAGE}/usr/bin/wordcraft
dst: /usr/bin/wordcraft
- src: ${STAGE}/usr/bin/${NFPM_BIN}
dst: /usr/bin/${NFPM_BIN}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/bin/wordcraft-cli
dst: /usr/bin/wordcraft-cli
- src: ${STAGE}/usr/bin/${NFPM_CLI}
dst: /usr/bin/${NFPM_CLI}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/lib/
dst: /usr/lib/
type: tree
# Named one by one rather than as a tree of /usr/share: a tree would also own shared directories
# such as /usr/share/mime, which openSUSE's filesystem package owns with other modes, and RPM
# refuses to install a package that conflicts with it.
- src: ${STAGE}/usr/share/applications/ai.storyteller.wordcraft.desktop
dst: /usr/share/applications/ai.storyteller.wordcraft.desktop
- src: ${STAGE}/usr/share/mime/packages/ai.storyteller.wordcraft.xml
dst: /usr/share/mime/packages/ai.storyteller.wordcraft.xml
- src: ${STAGE}/usr/share/metainfo/ai.storyteller.wordcraft.metainfo.xml
dst: /usr/share/metainfo/ai.storyteller.wordcraft.metainfo.xml
- src: ${STAGE}/usr/share/applications/${NFPM_APP_ID}.desktop
dst: /usr/share/applications/${NFPM_APP_ID}.desktop
- src: ${STAGE}/usr/share/mime/packages/${NFPM_APP_ID}.xml
dst: /usr/share/mime/packages/${NFPM_APP_ID}.xml
- src: ${STAGE}/usr/share/metainfo/${NFPM_APP_ID}.metainfo.xml
dst: /usr/share/metainfo/${NFPM_APP_ID}.metainfo.xml
- src: ${STAGE}/usr/share/icons/hicolor/
dst: /usr/share/icons/hicolor/
type: tree
- src: ${STAGE}/usr/share/doc/wordcraft/
dst: /usr/share/doc/wordcraft/
- src: ${STAGE}/usr/share/doc/${NFPM_NAME}/
dst: /usr/share/doc/${NFPM_NAME}/
type: tree
scripts:
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
real_bin="$(dirname "$0")/.wordcraft-nightly/wordcraft"
if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then
exec "$real_bin" "$@"
fi
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config}/wordcraft-nightly"
export XDG_DATA_HOME="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/wordcraft-nightly"
exec "$real_bin" "$@"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# Validate the staged Arch launcher without building or opening WordCraft.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
stage="$work/source"
dst="$work/dist"
base=wordcraft-0.0.1-nightly.1-linux-x86_64
mkdir -p "$stage/bin" "$dst" "$work/extract"
# A local argv/env recorder stands in for the compiled binaries. It never opens a UI.
cat >"$stage/bin/wordcraft" <<'RECORDER'
#!/bin/sh
printf 'XDG_CONFIG_HOME=%s\n' "${XDG_CONFIG_HOME:-}"
printf 'XDG_DATA_HOME=%s\n' "${XDG_DATA_HOME:-}"
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$stage/bin/wordcraft"
cp "$stage/bin/wordcraft" "$stage/bin/wordcraft-cli"
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
bin="$work/extract/$base/bin"
# Simulate the existing Arch bin-tree copy and public launcher rename.
mkdir -p "$work/installed"
cp -R "$bin" "$work/installed/bin"
bin="$work/installed/bin"
mv "$bin/wordcraft" "$bin/wordcraft-nightly"
mv "$bin/wordcraft-cli" "$bin/wordcraft-nightly-cli"
test ! -e "$stage/bin/.wordcraft-nightly"
cmp "$stage/bin/wordcraft" "$bin/.wordcraft-nightly/wordcraft"
cmp "$stage/bin/wordcraft-cli" "$bin/wordcraft-nightly-cli"
export HOME="$work/home with space"
unset XDG_CONFIG_HOME XDG_DATA_HOME
expect() {
expected="$1"
shift
actual=$(PATH="$bin:$PATH" wordcraft-nightly "$@")
if [[ "$actual" != "$expected" ]]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
expect "$(printf 'XDG_CONFIG_HOME=%s\nXDG_DATA_HOME=%s\n<>' "$HOME/.config/wordcraft-nightly" "$HOME/.local/share/wordcraft-nightly")"
export XDG_CONFIG_HOME="$work/xdg config with space"
export XDG_DATA_HOME="$work/xdg data with space"
expect "$(printf 'XDG_CONFIG_HOME=%s\nXDG_DATA_HOME=%s\n<%s>\n<%s>' "$XDG_CONFIG_HOME/wordcraft-nightly" "$XDG_DATA_HOME/wordcraft-nightly" 'doc with spaces.docx' '--other-name.docx')" \
'doc with spaces.docx' '--other-name.docx'
expect "$(printf 'XDG_CONFIG_HOME=%s\nXDG_DATA_HOME=%s\n<--version>' "$XDG_CONFIG_HOME" "$XDG_DATA_HOME")" --version
expect "$(printf 'XDG_CONFIG_HOME=%s\nXDG_DATA_HOME=%s\n<-V>' "$XDG_CONFIG_HOME" "$XDG_DATA_HOME")" -V
echo "PASS: Arch Nightly handoff isolates the profile and preserves launch arguments"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Stage the WordCraft Nightly-only handoff for the Arch packager.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
source_tree="$1"
work="$2"
destination="$3"
basename="$4"
stage="$work/$basename"
mkdir -p "$work"
cp -R "$source_tree" "$stage"
mkdir "$stage/bin/.wordcraft-nightly"
mv "$stage/bin/wordcraft" "$stage/bin/.wordcraft-nightly/wordcraft"
cp "$here/nightly-arch-launch.sh" "$stage/bin/wordcraft"
chmod 755 "$stage/bin/wordcraft"
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
echo "wrote $destination/$basename.tar.gz"
+142 -10
View File
@@ -7,7 +7,7 @@
# $DIST/wordcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
# $DIST/wordcraft-<version>-linux-<arch>.tar.gz plain FHS-style tree (bin/, share/)
#
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"]
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY]
#
# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage
# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04,
@@ -21,10 +21,16 @@ APP_ID=ai.storyteller.wordcraft
SKIP_BUILD=0
FORMATS="appimage deb rpm tar"
ARCH_TAR_DIR=
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-build) SKIP_BUILD=1; shift ;;
--formats) FORMATS="$2"; shift 2 ;;
--arch-tar-dir)
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
ARCH_TAR_DIR="$2"
shift 2
;;
-h | --help) sed -n '2,17p' "$0"; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
@@ -38,9 +44,24 @@ case "$ARCH" in
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
export WORDCRAFT_MAINTAINER="${WORDCRAFT_MAINTAINER:-WordCraft maintainers <[email protected]>}"
BASENAME="wordcraft-$VERSION-linux-$ARCH"
IS_NIGHTLY=0
if [[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
IS_NIGHTLY=1
export WORDCRAFT_BUILD_CHANNEL=nightly-v1
export WORDCRAFT_OVERRIDE_VERSION="$VERSION"
fi
BASENAME_VERSION="$VERSION"
if [[ "$IS_NIGHTLY" = 1 && "$BASENAME_VERSION" != *-nightly* ]]; then
BASENAME_VERSION="$BASENAME_VERSION-nightly"
fi
BASENAME="wordcraft-$BASENAME_VERSION-linux-$ARCH"
echo "==> WordCraft $VERSION for Linux $ARCH ($FORMATS)"
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
echo "error: --arch-tar-dir is only for Nightly builds" >&2
exit 2
fi
echo "==> WordCraft $VERSION for Linux $ARCH ($FORMATS, channel=${WORDCRAFT_BUILD_CHANNEL:-stable})"
if [[ "$SKIP_BUILD" = 0 ]]; then
if [[ -n "${CROSS_TARGET:-}" ]]; then
@@ -59,6 +80,11 @@ install -Dm755 "$BIN/wordcraft" "$STAGE/usr/bin/wordcraft"
install -Dm755 "$BIN/wordcraft-cli" "$STAGE/usr/bin/wordcraft-cli"
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/wordcraft" "$STAGE/usr/bin/wordcraft-cli" 2>/dev/null || true
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
if [[ "$IS_NIGHTLY" = 1 ]]; then
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
"$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp"
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
fi
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
mkdir -p "$STAGE/usr/share/metainfo"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$WORDCRAFT_BUILD_DATE/g" \
@@ -85,13 +111,81 @@ if has tar; then
echo "wrote $DIST/$BASENAME.tar.gz"
fi
# The Arch handoff keeps the same basename as the plain tarball in a separate directory.
# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher.
if [[ -n "$ARCH_TAR_DIR" ]]; then
mkdir -p "$ARCH_TAR_DIR"
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
echo "error: the Arch tar directory must differ from the release directory" >&2
exit 2
fi
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
fi
# ---- .deb / .rpm --------------------------------------------------------------------------------
if has deb || has rpm; then
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
export VERSION
export NFPM_ARCH="$DEB_ARCH"
NFPM_STAGE="$STAGE"
export NFPM_NAME="wordcraft"
export NFPM_BIN="wordcraft"
export NFPM_CLI="wordcraft-cli"
export NFPM_APP_ID="$APP_ID"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
export NFPM_NAME="wordcraft-nightly"
export NFPM_BIN="wordcraft-nightly"
export NFPM_CLI="wordcraft-nightly-cli"
export NFPM_APP_ID="$NIGHTLY_DESK_ID"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
install -Dm755 "$NFPM_STAGE/usr/bin/wordcraft" "$NFPM_STAGE/usr/lib/wordcraft-nightly/wordcraft"
cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER'
#!/bin/sh
set -eu
if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then
exec /usr/lib/wordcraft-nightly/wordcraft "$@"
fi
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config}/wordcraft-nightly"
export XDG_DATA_HOME="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/wordcraft-nightly"
exec /usr/lib/wordcraft-nightly/wordcraft "$@"
WRAPPER
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN"
rm -f "$NFPM_STAGE/usr/bin/wordcraft"
mv "$NFPM_STAGE/usr/bin/wordcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
mv "$NFPM_STAGE/usr/share/doc/wordcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s|^Exec=wordcraft\([[:space:]]\|$\)|Exec=$NFPM_BIN\1|" \
-e "s|^TryExec=wordcraft$|TryExec=$NFPM_BIN|" \
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
-e '/^MimeType=/d' \
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
-e "s|<name>WordCraft</name>|<name>WordCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$NIGHTLY_DESK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$NIGHTLY_DESK_ID</icon>|g" \
-e "s|<binary>wordcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$NFPM_STAGE/usr/share/mime"
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
fi
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
DROP_LIB_TREE=
# shellcheck disable=SC2016
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
DROP_MIME=
# shellcheck disable=SC2016
[[ -f "$NFPM_STAGE/usr/share/mime/packages/$NFPM_APP_ID.xml" ]] || DROP_MIME='\|^ - src: \${STAGE}/usr/share/mime/packages/|,+1d;'
# shellcheck disable=SC2016
sed "${DROP_LIB_TREE}${DROP_MIME}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g;s|\${NFPM_APP_ID}|$NFPM_APP_ID|g;s|\${NFPM_NAME}|$NFPM_NAME|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
for fmt in deb rpm; do
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
done
@@ -131,10 +225,39 @@ if has appimage; then
}
APPDIR="$WORK/WordCraft.AppDir"
cp -R "$STAGE" "$APPDIR"
ln -s usr/bin/wordcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
if [[ "$IS_NIGHTLY" = 1 ]]; then
APPIMAGE_ID="$APP_ID.nightly-v1"
cat >"$APPDIR/AppRun" <<'WRAPPER'
#!/bin/sh
set -eu
HERE="$(dirname "$(readlink -f "$0")")"
if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then
exec "$HERE/usr/bin/wordcraft" "$@"
fi
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config}/wordcraft-nightly"
export XDG_DATA_HOME="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/wordcraft-nightly"
exec "$HERE/usr/bin/wordcraft" "$@"
WRAPPER
chmod 755 "$APPDIR/AppRun"
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
-e '/^MimeType=/d' \
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
rm -rf "$APPDIR/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
else
ln -s usr/bin/wordcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
fi
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
if [[ -z "$TOOL" ]]; then
@@ -162,12 +285,21 @@ if has appimage; then
# each AppImage on GitHub Releases. `latest` is the newest published release that is not a
# pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
REPO="${GITHUB_REPOSITORY:-storytold/wordcraft}"
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|wordcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=()
if [[ "$IS_NIGHTLY" = 0 ]]; then
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|wordcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
else
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
# zsync update metadata at pre-release tags matching `-nightly` rather than stable `latest`.
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|wordcraft-*-nightly*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
fi
# Extract-and-run: works without FUSE (containers, CI). The output embeds the pinned static
# runtime, so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream \
--runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT")
--runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
echo "wrote $OUT"
if [[ -s "$OUT.zsync" ]]; then
echo "wrote $OUT.zsync"
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""Local regression checks for WordCraft's supervised manual nightly workflows and v3 policy."""
import copy
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
def assert_nightly_serialization(source):
"""Fail closed unless this app's plain root concurrency block retains its contract.
This is a deliberately narrow source guard, not a general YAML parser; actionlint
still checks all other syntax. Expressions, aliases and alternate block shapes
refuse rather than delegating queue-value validation to the old linter.
"""
lines = source.splitlines()
roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")]
if len(roots) != 1 or lines[roots[0]] != "concurrency:":
raise ValueError("one plain root concurrency block is required")
values = {}
for line in lines[roots[0] + 1:]:
if not line.strip() or line.lstrip().startswith("#"):
continue
if not line[0].isspace():
break
row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line)
if row is None or row[1] in values:
raise ValueError("malformed or duplicate nightly concurrency entry")
values[row[1]] = row[2].rstrip()
if values != {"group": "wordcraft-nightly-release", "cancel-in-progress": "false"}:
raise ValueError("nightly serialization must use its stable group and no cancellation")
def literal_off(condition):
expression = " ".join(condition.split())
if expression.startswith("${{") and expression.endswith("}}"):
expression = expression[3:-2].strip()
if expression == "false":
return True
if not expression.startswith("false && "):
return False
# A top-level OR could override the leading false; parentheses must balance.
expression = re.sub(r"'(?:''|[^'])*'", "''", expression)
depth = 0
for token in re.findall(r"\(|\)|\|\|", expression):
if token == "(":
depth += 1
elif token == ")":
depth -= 1
if depth < 0:
return False
elif depth == 0:
return False
return depth == 0
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read).
A narrow source reader, not a YAML parser: every following line indented deeper than the
job keys continues the value, for block scalars and plain multi-line scalars alike, so a
continuation line can never hide from the guard checks.
"""
lines = jobs.splitlines()
found = []
for index, line in enumerate(lines):
head = re.fullmatch(r" if:(?: (.*))?", line)
if head is None:
continue
value = (head[1] or "").strip()
continuation = []
for follow in lines[index + 1:]:
if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4:
break
continuation.append(follow.strip())
indicator = value if re.fullmatch(r"[>|][+-]?", value) else None
parts = continuation if indicator else [value] + continuation
found.append((indicator, " ".join(part for part in parts if part)))
return found
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
"linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"),
"macos-aarch64": ("apple_team_id", "DJ6XS33FX8"),
}
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
# Update by PR, in the caller and the policy, when the team changes.
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
def producer_platforms(source):
"""Read the one producer job's literal platform list; a narrow source guard, not YAML.
One producer run builds every listed platform for one all-or-nothing release, so the
list must be a compact JSON list of distinct known platforms that keeps Windows.
"""
rows = re.findall(r"(?m)^ platforms: (.*)$", source)
if len(rows) != 1:
raise ValueError("exactly one producer platform list is required")
literal = re.fullmatch(r"'(\[[^']*\])'", rows[0])
if literal is None:
raise ValueError("the platform list must be one single-quoted literal")
platforms = json.loads(literal[1])
if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]:
raise ValueError("the platform list must be compact JSON")
if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS):
raise ValueError("platforms must be distinct known nightly targets")
if "windows-x86_64" not in platforms:
raise ValueError("the Windows row stays in the producer")
return platforms
def reviewed_manual_actors(caller_source, policy):
"""The one reviewed manual-actor list, identical in the producer caller and the policy."""
rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source)
if len(rows) != 1:
raise ValueError("exactly one literal manual-actors list is required")
caller = json.loads(rows[0])
if caller != policy["manual_actors"]:
raise ValueError("caller and policy must grant the same actors in the same order")
if caller != RELEASE_MANAGERS:
raise ValueError("manual actors must be exactly the reviewed release managers")
if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller):
raise ValueError("manual actors must be distinct and sorted case-insensitively")
if set(caller) & {login for login in policy["automatic_signer_actors"]}:
raise ValueError("manual and automatic actors overlap")
return caller
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0]
class TrustedSourcePreparation(unittest.TestCase):
def test_one_producer_and_one_signer_job_carry_every_platform(self):
for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")):
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
with self.subTest(workflow=name):
self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job],
"a platform is a list entry, not a separately activatable job")
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms")
def test_malformed_or_narrowed_platform_lists_are_rejected(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'"
self.assertIn(current, source)
for new in ("platforms: '[\"linux-x86_64\"]'",
"platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'",
"platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'",
"platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'",
"platforms: '[\"windows-x86_64\",\"linux-arm64\"]'",
"platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'",
"platforms: [\"windows-x86_64\",\"linux-x86_64\"]",
"platforms: ${{ vars.NIGHTLY_PLATFORMS }}",
"platforms: '{\"windows-x86_64\":1}'",
current + "\n " + current):
with self.subTest(change=new), self.assertRaises(ValueError):
producer_platforms(source.replace(current, new))
with self.assertRaises(ValueError):
producer_platforms(source.replace(" " + current + "\n", ""))
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
source = (ROOT / ".github/workflows" / workflow).read_text()
expected = NightlyEnabledCallers.GUARDS[name]
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1]
with self.subTest(workflow=name, replacement=replacement[-30:]):
(indicator, expression), = job_conditions(jobs)
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
def test_dormancy_guard_rejects_activation_and_top_level_or(self):
for condition in ("true", "vars.ENABLE_NIGHTLY", "false || true", "false && true || true",
"false && (true || true", "false && true) || true"):
with self.subTest(condition=condition):
self.assertFalse(literal_off(condition))
self.assertTrue(literal_off("${{ false }}"))
self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')"))
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-sign.yml", "workflow_dispatch")):
source = (ROOT / ".github/workflows" / name).read_text()
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
triggers = [line for line in events.splitlines() if line.startswith(" ")
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
with self.subTest(workflow=name):
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
def test_weakened_or_malformed_serialization_is_rejected(self):
source = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
for old, new in (
("cancel-in-progress: false", "cancel-in-progress: true"),
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
("cancel-in-progress: false\n", ""),
("group: wordcraft-nightly-release", "group: ${{ github.run_id }}"),
("group: wordcraft-nightly-release", "group: release-${{ github.ref }}"),
("concurrency:\n", "concurrency: ${{ github.run_id }}\n"),
("concurrency:\n", " concurrency:\n"),
):
with self.subTest(change=new), self.assertRaises(ValueError):
assert_nightly_serialization(source.replace(old, new))
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
for name in ("nightly.yml", "nightly-sign.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
class NightlyTrustAnchors(unittest.TestCase):
"""The public stable identities each platform's signed nightly must carry (all three platforms)."""
def setUp(self):
self.policy = json.loads(INSTALLED_POLICY.read_text())
def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self):
self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST))
for platform, (field, value) in NIGHTLY_TRUST.items():
row = self.policy["platforms"][platform]
with self.subTest(platform=platform):
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}",
"the artifact kind is fixed by platform, never a caller pattern")
self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity")
def test_trust_values_have_the_shapes_the_shared_signer_accepts(self):
rows = self.policy["platforms"]
self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$")
self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$")
subject = rows["windows-x86_64"]["trust"]["publisher_subject"]
self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"})
def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self):
pins = set()
for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")):
source = (ROOT / ".github/workflows" / name).read_text()
uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/"
+ re.escape(callee) + r"@(\S+)$", source)
tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source)
with self.subTest(workflow=name):
self.assertEqual(len(uses), 1)
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
class NightlyEnabledCallers(unittest.TestCase):
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
GUARDS = {
"nightly.yml": "github.repository == 'storytold/wordcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/wordcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
}
def test_enabled_jobs_keep_exact_context_guards(self):
for name, expected in self.GUARDS.items():
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
guards = job_conditions(jobs)
with self.subTest(workflow=name):
self.assertEqual(len(guards), 1)
indicator, expression = guards[0]
self.assertEqual(indicator, ">-")
self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review")
def test_manual_actors_are_the_release_managers_in_caller_and_policy(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":"))
widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower)
for change in ("caller", "policy", "both", "order", "case"):
mutated_source, mutated_policy = source, copy.deepcopy(policy)
if change in ("caller", "both"):
mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":")))
if change in ("policy", "both"):
mutated_policy["manual_actors"] = widened
if change == "order":
mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS))
if change == "case":
mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS]
with self.subTest(change=change), self.assertRaises(ValueError):
reviewed_manual_actors(mutated_source, mutated_policy)
class NightlyInstalledPolicy(unittest.TestCase):
"""The installed v3 policy matches the callers, the repository and its documented sources."""
EXPECTED_KEYS = {
"schema", "repository", "repository_id", "producer_workflow_id",
"producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref",
"signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors",
"automatic_signer_actors", "max_age_seconds", "candidate_policy",
"max_artifact_bytes", "platforms",
}
def setUp(self):
self.assertFalse(INSTALLED_POLICY.is_symlink())
self.policy = json.loads(INSTALLED_POLICY.read_text())
def test_exact_v3_fields_and_repository_identity(self):
self.assertEqual(set(self.policy), self.EXPECTED_KEYS)
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(self.policy["repository"], "storytold/wordcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
# producer_workflow_id is null until nightly.yml is registered on main, then a positive int.
producer_id = self.policy["producer_workflow_id"]
if producer_id is not None:
self.assertIs(type(producer_id), int)
self.assertGreater(producer_id, 0)
self.assertNotEqual(producer_id,
self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"],
"the producer is not its own quality workflow")
def test_paths_and_tooling_match_the_callers(self):
pin = caller_pin("nightly.yml")
self.assertEqual(caller_pin("nightly-sign.yml"), pin)
self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml")
self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml")
self.assertEqual(self.policy["producer_tooling_revision"], pin)
self.assertEqual(self.policy["signer_tooling_revision"], pin)
self.assertEqual(self.policy["producer_workflow_ref"],
"storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin)
def test_platforms_equal_the_producer(self):
built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text())
self.assertEqual(built, list(NIGHTLY_PLATFORMS), "one release carries Windows, Linux and macOS")
self.assertEqual(set(self.policy["platforms"]), set(built))
def test_bounds(self):
self.assertIs(type(self.policy["max_age_seconds"]), int)
self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800)
self.assertIs(type(self.policy["max_artifact_bytes"]), int)
self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3)
def test_candidate_workflows_run_on_every_main_push(self):
candidate = self.policy["candidate_policy"]
self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"})
self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3")
self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/wordcraft", "main"))
self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128)
rows = candidate["required_workflows"]
self.assertTrue(rows)
for row in rows:
with self.subTest(workflow=row["workflow_path"]):
self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"})
self.assertIs(type(row["workflow_id"]), int)
self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"])
source = (ROOT / row["workflow_path"]).read_text()
push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source)
self.assertIsNotNone(push, "a required workflow must run on main pushes")
self.assertIn(" branches: [main]\n", push[1])
self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run")
names = [job["name"] for job in row["jobs"]]
self.assertEqual(len(names), len(set(names)))
for job in row["jobs"]:
self.assertEqual(set(job), {"name", "app_id", "applicability"})
self.assertEqual((job["app_id"], job["applicability"]), (15368, "required"))
def test_sonar_identity_and_reviewed_scope(self):
sonar = self.policy["candidate_policy"]["sonar"]
properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines()
if line and not line.startswith("#"))
self.assertEqual(sonar["organization"], properties["sonar.organization"])
self.assertEqual(sonar["project"], properties["sonar.projectKey"])
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]))
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
self.assertEqual(len(metrics), len(set(metrics)))
keys = [item["key"] for item in sonar["debt"]]
self.assertEqual(len(keys), len(set(keys)))
for item in sonar["debt"]:
with self.subTest(issue=item["key"]):
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
self.assertIn(item["type"], sonar["issue_types"])
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
if __name__ == "__main__":
unittest.main(verbosity=2)