From 60e9ae022278865134d75a2c6df24c1dfc403bd3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:44 +0700 Subject: [PATCH 01/10] =?UTF-8?q?i18n:=20fill-handle=20and=20Home=20?= =?UTF-8?q?=E2=80=BA=20Fill=20menu=20labels=20in=20every=20catalog=20(#445?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The right-drag fill menu and the Auto Fill Options button (Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Fill Days, Fill Weekdays, Fill Months, Fill Years and the button's own name) had no row in any catalog, so every language showed them in English. Add them to all 18 non-English catalogs, add Series…, Down and Up from the Home › Fill menu to the nine catalogs that lacked them, and translate the Ukrainian rows that held English. fill_menu_labels_are_translated_in_every_catalog fails when one of these rows goes missing or stays English. Fixes #4458 Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/i18n.rs | 29 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.rs | 9 +++++++++ crates/ui-egui/src/i18n/de.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/el.rs | 9 +++++++++ crates/ui-egui/src/i18n/es.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/fr.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/it.rs | 9 +++++++++ crates/ui-egui/src/i18n/ja.rs | 9 +++++++++ crates/ui-egui/src/i18n/ko.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/nl.rs | 9 +++++++++ crates/ui-egui/src/i18n/pl.rs | 9 +++++++++ crates/ui-egui/src/i18n/pt.rs | 9 +++++++++ crates/ui-egui/src/i18n/ro.rs | 9 +++++++++ crates/ui-egui/src/i18n/ru.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/sr.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/tr.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/uk.rs | 15 ++++++++++++--- crates/ui-egui/src/i18n/vi.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/zh.rs | 12 ++++++++++++ docs/localization-parity.md | 3 ++- 20 files changed, 223 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 6f5036c80f..0b25ccecf6 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -532,6 +532,35 @@ mod tests { } } + /// The fill-handle menus (the right-drag menu and the Auto Fill Options button) and the + /// Home › Fill menu have a row in every catalog, with no silent English fallback (#4458). + #[test] + fn fill_menu_labels_are_translated_in_every_catalog() { + let keys = [ + "Copy Cells", + "Fill Series", + "Fill Formatting Only", + "Fill Without Formatting", + "Fill Days", + "Fill Weekdays", + "Fill Months", + "Fill Years", + "Auto Fill Options", + "Series…", + "Down", + "Up", + ]; + for key in keys { + assert_eq!(Language::En.tr(key), key); + for language in Language::ALL.into_iter().filter(|l| *l != Language::En) { + let code = language.code(); + let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}")); + assert!(!shown.trim().is_empty() && !shown.contains('\n'), "{code}: bad translation of {key:?}: {shown:?}"); + assert_ne!(shown, key, "{code}: the row for {key:?} is still English"); + } + } + } + #[test] fn fill_puts_each_value_in_once() { // A value holding a placeholder (a macro named `{steps}`) is shown as it is. diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index a7464598a3..7fbf474c57 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -728,6 +728,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char má nečíselný argument {argument}", "\\@char with invalid code point {code}" => "\\@char s neplatným kódovým bodem {code}", "Invalid environment name character: {character}" => "Neplatný znak v názvu prostředí: {character}", + "Copy Cells" => "Kopírovat buňky", + "Fill Series" => "Vyplnit řady", + "Fill Formatting Only" => "Vyplnit pouze formáty", + "Fill Without Formatting" => "Vyplnit bez formátování", + "Fill Days" => "Vyplnit dny", + "Fill Weekdays" => "Vyplnit pracovní dny", + "Fill Months" => "Vyplnit měsíce", + "Fill Years" => "Vyplnit roky", + "Auto Fill Options" => "Možnosti automatického vyplnění", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 300cc4969a..e1490bb96e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -650,6 +650,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char hat ein nicht numerisches Argument {argument}", "\\@char with invalid code point {code}" => "\\@char mit ungültigem Codepunkt {code}", "Invalid environment name character: {character}" => "Ungültiges Zeichen im Umgebungsnamen: {character}", + "Copy Cells" => "Zellen kopieren", + "Fill Series" => "Datenreihe ausfüllen", + "Fill Formatting Only" => "Nur Formate ausfüllen", + "Fill Without Formatting" => "Ohne Formatierung ausfüllen", + "Fill Days" => "Tage ausfüllen", + "Fill Weekdays" => "Wochentage ausfüllen", + "Fill Months" => "Monate ausfüllen", + "Fill Years" => "Jahre ausfüllen", + "Auto Fill Options" => "Optionen für automatisches Ausfüllen", + "Series…" => "Reihe…", + "Down" => "Nach unten", + "Up" => "Nach oben", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 1287ad6a02..b5cab06d06 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -1135,6 +1135,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "Το \\@char έχει μη αριθμητικό όρισμα {argument}", "\\@char with invalid code point {code}" => "\\@char με μη έγκυρο σημείο κώδικα {code}", "Invalid environment name character: {character}" => "Μη έγκυρος χαρακτήρας στο όνομα περιβάλλοντος: {character}", + "Copy Cells" => "Αντιγραφή κελιών", + "Fill Series" => "Συμπλήρωση σειράς", + "Fill Formatting Only" => "Συμπλήρωση μόνο μορφοποίησης", + "Fill Without Formatting" => "Συμπλήρωση χωρίς μορφοποίηση", + "Fill Days" => "Συμπλήρωση ημερών", + "Fill Weekdays" => "Συμπλήρωση εργάσιμων ημερών", + "Fill Months" => "Συμπλήρωση μηνών", + "Fill Years" => "Συμπλήρωση ετών", + "Auto Fill Options" => "Επιλογές αυτόματης συμπλήρωσης", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d0df42c8b2..d318e998fc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -656,6 +656,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char tiene un argumento no numérico {argument}", "\\@char with invalid code point {code}" => "\\@char con un punto de código no válido {code}", "Invalid environment name character: {character}" => "Carácter no válido en el nombre del entorno: {character}", + "Copy Cells" => "Copiar celdas", + "Fill Series" => "Rellenar serie", + "Fill Formatting Only" => "Rellenar solo formatos", + "Fill Without Formatting" => "Rellenar sin formato", + "Fill Days" => "Rellenar días", + "Fill Weekdays" => "Rellenar días laborables", + "Fill Months" => "Rellenar meses", + "Fill Years" => "Rellenar años", + "Auto Fill Options" => "Opciones de autorrelleno", + "Series…" => "Serie…", + "Down" => "Hacia abajo", + "Up" => "Hacia arriba", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 104edcd161..1fdcb1279c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -618,6 +618,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char a un argument non numérique {argument}", "\\@char with invalid code point {code}" => "\\@char avec un point de code non valide {code}", "Invalid environment name character: {character}" => "Caractère non valide dans le nom d'environnement : {character}", + "Copy Cells" => "Copier les cellules", + "Fill Series" => "Remplir la série", + "Fill Formatting Only" => "Remplir les formats uniquement", + "Fill Without Formatting" => "Remplir sans la mise en forme", + "Fill Days" => "Remplir les jours", + "Fill Weekdays" => "Remplir les jours ouvrés", + "Fill Months" => "Remplir les mois", + "Fill Years" => "Remplir les années", + "Auto Fill Options" => "Options de remplissage automatique", + "Series…" => "Série…", + "Down" => "Vers le bas", + "Up" => "Vers le haut", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1ca07d34b0..1154e17385 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1139,6 +1139,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char ha un argomento non numerico {argument}", "\\@char with invalid code point {code}" => "\\@char con punto di codice non valido {code}", "Invalid environment name character: {character}" => "Carattere non valido nel nome dell'ambiente: {character}", + "Copy Cells" => "Copia celle", + "Fill Series" => "Riempi serie", + "Fill Formatting Only" => "Riempi solo formattazione", + "Fill Without Formatting" => "Riempi senza formattazione", + "Fill Days" => "Riempi giorni", + "Fill Weekdays" => "Riempi giorni feriali", + "Fill Months" => "Riempi mesi", + "Fill Years" => "Riempi anni", + "Auto Fill Options" => "Opzioni di riempimento automatico", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f5d9baa2ac..3033b55e56 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1288,6 +1288,15 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ "Drag to fill cells. Drag from inside a cell to select a range.", "ドラッグしてセルをオートフィルします。セルの内側からドラッグすると範囲を選択します。", ), + ("Copy Cells", "セルのコピー"), + ("Fill Series", "連続データを入力"), + ("Fill Formatting Only", "書式のみを入力"), + ("Fill Without Formatting", "書式なしで入力"), + ("Fill Days", "日単位で入力"), + ("Fill Weekdays", "平日単位で入力"), + ("Fill Months", "月単位で入力"), + ("Fill Years", "年単位で入力"), + ("Auto Fill Options", "オートフィル オプション"), ]; /// Translates an interface label; `None` for a label the catalog does not know, so `i18n.rs` can diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 880f97ac84..2e5b7660f0 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -616,6 +616,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char 의 인수 {argument} 이(가) 숫자가 아닙니다", "\\@char with invalid code point {code}" => "\\@char 의 코드 포인트 {code} 이(가) 잘못되었습니다", "Invalid environment name character: {character}" => "환경 이름에 잘못된 문자가 있습니다: {character}", + "Copy Cells" => "셀 복사", + "Fill Series" => "연속 데이터 채우기", + "Fill Formatting Only" => "서식만 채우기", + "Fill Without Formatting" => "서식 없이 채우기", + "Fill Days" => "일 단위 채우기", + "Fill Weekdays" => "평일 단위 채우기", + "Fill Months" => "월 단위 채우기", + "Fill Years" => "연 단위 채우기", + "Auto Fill Options" => "자동 채우기 옵션", + "Series…" => "연속 데이터…", + "Down" => "아래쪽", + "Up" => "위쪽", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index ea0352af32..8267b65efe 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -691,6 +691,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char heeft een niet-numeriek argument {argument}", "\\@char with invalid code point {code}" => "\\@char met ongeldig codepunt {code}", "Invalid environment name character: {character}" => "Ongeldig teken in de omgevingsnaam: {character}", + "Copy Cells" => "Cellen kopiëren", + "Fill Series" => "Reeks vullen", + "Fill Formatting Only" => "Alleen opmaak vullen", + "Fill Without Formatting" => "Vullen zonder opmaak", + "Fill Days" => "Dagen vullen", + "Fill Weekdays" => "Werkdagen vullen", + "Fill Months" => "Maanden vullen", + "Fill Years" => "Jaren vullen", + "Auto Fill Options" => "Opties voor automatisch vullen", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index b7b5882055..0b774cbf11 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1127,6 +1127,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char ma nienumeryczny argument {argument}", "\\@char with invalid code point {code}" => "\\@char z nieprawidłowym punktem kodowym {code}", "Invalid environment name character: {character}" => "Nieprawidłowy znak w nazwie środowiska: {character}", + "Copy Cells" => "Kopiuj komórki", + "Fill Series" => "Wypełnij serią", + "Fill Formatting Only" => "Wypełnij tylko formatami", + "Fill Without Formatting" => "Wypełnij bez formatowania", + "Fill Days" => "Wypełnij dniami", + "Fill Weekdays" => "Wypełnij dniami roboczymi", + "Fill Months" => "Wypełnij miesiącami", + "Fill Years" => "Wypełnij latami", + "Auto Fill Options" => "Opcje autowypełniania", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 168450222f..a26216f1ba 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -1143,6 +1143,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char tem um argumento não numérico {argument}", "\\@char with invalid code point {code}" => "\\@char com ponto de código inválido {code}", "Invalid environment name character: {character}" => "Caractere inválido no nome do ambiente: {character}", + "Copy Cells" => "Copiar Células", + "Fill Series" => "Preencher Série", + "Fill Formatting Only" => "Preencher Somente Formatos", + "Fill Without Formatting" => "Preencher Sem Formatação", + "Fill Days" => "Preencher Dias", + "Fill Weekdays" => "Preencher Dias Úteis", + "Fill Months" => "Preencher Meses", + "Fill Years" => "Preencher Anos", + "Auto Fill Options" => "Opções de Autopreenchimento", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index ad47d70115..e4b1ab3c76 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -1189,6 +1189,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char are un argument nenumeric {argument}", "\\@char with invalid code point {code}" => "\\@char cu punct de cod nevalid {code}", "Invalid environment name character: {character}" => "Caracter nevalid în numele mediului: {character}", + "Copy Cells" => "Copiere celule", + "Fill Series" => "Umplere serie", + "Fill Formatting Only" => "Umplere doar formate", + "Fill Without Formatting" => "Umplere fără formatare", + "Fill Days" => "Umplere zile", + "Fill Weekdays" => "Umplere zile lucrătoare", + "Fill Months" => "Umplere luni", + "Fill Years" => "Umplere ani", + "Auto Fill Options" => "Opțiuni de umplere automată", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 77a3874429..3f861bb2fd 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -626,6 +626,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "У \\@char нечисловой аргумент {argument}", "\\@char with invalid code point {code}" => "\\@char с недопустимой кодовой точкой {code}", "Invalid environment name character: {character}" => "Недопустимый символ в имени окружения: {character}", + "Copy Cells" => "Копировать ячейки", + "Fill Series" => "Заполнить ряд", + "Fill Formatting Only" => "Заполнить только форматы", + "Fill Without Formatting" => "Заполнить без форматирования", + "Fill Days" => "Заполнить по дням", + "Fill Weekdays" => "Заполнить по рабочим дням", + "Fill Months" => "Заполнить по месяцам", + "Fill Years" => "Заполнить по годам", + "Auto Fill Options" => "Параметры автозаполнения", + "Series…" => "Ряд…", + "Down" => "Вниз", + "Up" => "Вверх", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 4b65ab8be3..5aabbf7b1a 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -609,6 +609,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char ima nenumerički argument {argument}", "\\@char with invalid code point {code}" => "\\@char sa nevažećom kodnom tačkom {code}", "Invalid environment name character: {character}" => "Nevažeći znak u nazivu okruženja: {character}", + "Copy Cells" => "Kopiraj ćelije", + "Fill Series" => "Popuni niz", + "Fill Formatting Only" => "Popuni samo oblikovanja", + "Fill Without Formatting" => "Popuni bez oblikovanja", + "Fill Days" => "Popuni dane", + "Fill Weekdays" => "Popuni radne dane", + "Fill Months" => "Popuni mesece", + "Fill Years" => "Popuni godine", + "Auto Fill Options" => "Opcije automatskog popunjavanja", + "Series…" => "Niz…", + "Down" => "Nadole", + "Up" => "Nagore", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index e2d27fbf06..ca59a0dd98 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -581,6 +581,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char sayısal olmayan bir bağımsız değişkene sahip: {argument}", "\\@char with invalid code point {code}" => "\\@char geçersiz bir kod noktası içeriyor: {code}", "Invalid environment name character: {character}" => "Ortam adında geçersiz karakter: {character}", + "Copy Cells" => "Hücreleri Kopyala", + "Fill Series" => "Seriyi Doldur", + "Fill Formatting Only" => "Yalnızca Biçimleri Doldur", + "Fill Without Formatting" => "Biçimlendirmeden Doldur", + "Fill Days" => "Günleri Doldur", + "Fill Weekdays" => "İş Günlerini Doldur", + "Fill Months" => "Ayları Doldur", + "Fill Years" => "Yılları Doldur", + "Auto Fill Options" => "Otomatik Doldurma Seçenekleri", + "Series…" => "Seri…", + "Down" => "Aşağı", + "Up" => "Yukarı", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 185a21c1d1..33141bdfff 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -907,7 +907,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Delete chart" => "Видалити діаграму", "Delete…" => "Delete…", "Dismiss" => "Dismiss", - "Down" => "Down", + "Down" => "Вниз", "Edit chart title" => "Редагувати назву діаграми", "Erase ink strokes" => "Erase ink strokes", "Every command run in this session (replayable)" => "Every command run in this session (replayable)", @@ -954,7 +954,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Search and run any command" => "Search and run any command", "Search commands" => "Search commands", "Select and move ink and shapes" => "Select and move ink and shapes", - "Series…" => "Series…", + "Series…" => "Ряд…", "Share: export or save a copy" => "Share: export or save a copy", "Show Formulas (⌃`)" => "Show Formulas (⌃`)", "Slicer" => "Slicer", @@ -969,7 +969,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Undo" => "Undo", "Undo list" => "Undo list", "Unhide Sheet…" => "Unhide Sheet…", - "Up" => "Up", + "Up" => "Угору", "Version, contributors and the AI models that helped" => "Version, contributors and the AI models that helped", "What-If Analysis" => "What-If Analysis", "Zoom In" => "Zoom In", @@ -1131,6 +1131,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char має нечисловий аргумент {argument}", "\\@char with invalid code point {code}" => "\\@char з неприпустимою кодовою точкою {code}", "Invalid environment name character: {character}" => "Неприпустимий символ у назві середовища: {character}", + "Copy Cells" => "Копіювати комірки", + "Fill Series" => "Заповнити ряд", + "Fill Formatting Only" => "Заповнити лише формати", + "Fill Without Formatting" => "Заповнити без форматування", + "Fill Days" => "Заповнити дні", + "Fill Weekdays" => "Заповнити робочі дні", + "Fill Months" => "Заповнити місяці", + "Fill Years" => "Заповнити роки", + "Auto Fill Options" => "Параметри автозаповнення", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 93dd959379..100230d026 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -577,6 +577,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char có đối số không phải số {argument}", "\\@char with invalid code point {code}" => "\\@char có điểm mã không hợp lệ {code}", "Invalid environment name character: {character}" => "Ký tự không hợp lệ trong tên môi trường: {character}", + "Copy Cells" => "Sao chép ô", + "Fill Series" => "Điền chuỗi", + "Fill Formatting Only" => "Chỉ điền định dạng", + "Fill Without Formatting" => "Điền không kèm định dạng", + "Fill Days" => "Điền theo ngày", + "Fill Weekdays" => "Điền theo ngày làm việc", + "Fill Months" => "Điền theo tháng", + "Fill Years" => "Điền theo năm", + "Auto Fill Options" => "Tùy chọn tự động điền", + "Series…" => "Chuỗi…", + "Down" => "Xuống", + "Up" => "Lên", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index b57d3292df..36e1d4ccad 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -600,6 +600,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char 的参数 {argument} 不是数字", "\\@char with invalid code point {code}" => "\\@char 的码位 {code} 无效", "Invalid environment name character: {character}" => "环境名称中有无效字符: {character}", + "Copy Cells" => "复制单元格", + "Fill Series" => "填充序列", + "Fill Formatting Only" => "仅填充格式", + "Fill Without Formatting" => "不带格式填充", + "Fill Days" => "以天数填充", + "Fill Weekdays" => "以工作日填充", + "Fill Months" => "以月填充", + "Fill Years" => "以年填充", + "Auto Fill Options" => "自动填充选项", + "Series…" => "序列…", + "Down" => "向下", + "Up" => "向上", _ => return None, }) } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index d3f94425ce..c32c2c3be0 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (RaTeX equation parser messages follow the interface language); previously minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (fill-handle and Home › Fill menu labels in every catalog); previously minor (RaTeX equation parser messages follow the interface language); previously minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Per-language status against Excel, which ships its UI in dozens of languages (Windows language packs cover 100+), with localized function names, argument separators, number and date formats, @@ -146,6 +146,7 @@ language (none so far) and of localized function names. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | The fill-handle menus (right-drag menu and Auto Fill Options: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Fill Days, Fill Weekdays, Fill Months, Fill Years, and the button's own name) have a row in all 18 non-English catalogs, and Series…, Down and Up from the Home › Fill menu in the nine catalogs that lacked them; the Ukrainian rows that held English are translated. A test fails when one goes missing (#4458). The translations are AI-assisted and not yet reviewed by native speakers | | 2026-11-15 | minor | The RaTeX equation parser's messages follow the interface language: its 33 fixed messages are catalog keys, and its 33 messages that carry a piece of the source (a command, token, environment name or count) are read back into templates (`i18n::unfill`) whose translation is filled with the same pieces. A message of another shape, such as RaTeX's internal ones or the chemistry parser's, stays English. 66 new keys in every catalog (#4261) | | 2026-11-10 | minor | Ukrainian Chart is `Діаграма`, matching [craft-i18n#211](https://github.com/storytold/craft-i18n/pull/211) and distinct from Diagram (`Схема`) | | 2026-11-10 | minor | Diagram and Decorative Text labels in all 18 non-English catalogs; Diagram never repeats the catalog's chart word (German `Schema`, Ukrainian `Схема`, Romanian `Schemă`), see [feature-names.md](feature-names.md) | From 927d4d60a6da2db2971b82994f0b79ac7aba3faf Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:34:15 +0700 Subject: [PATCH 02/10] test(io): tolerate errno 45 as ENOTSUP when this host's std does (#4656) Fixes #4655. Since #3178, the scheduled FreeBSD 15 x86_64 job has failed io::tests::full_sync_tolerates_apple_enotsup with "45 on other Unix". The test assumed errno 45 is never ErrorKind::Unsupported unless the Apple flag is set. That is true on Linux (EL2NSYNC) but not on FreeBSD, where 45 is ENOTSUP and equals EOPNOTSUPP. Production full_sync_unsupported is already correct on FreeBSD via kind(). This change makes those two unit-test cases follow the host mapping, so Linux still requires a failed save and BSD hosts match production. No production code change. The FreeBSD aarch64 job only cross-compiles tests; it does not run them, so a green aarch64 leg is not a test pass. --- crates/engine/src/io/tests.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index 9c4127f1da..4a775bd56d 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -409,16 +409,19 @@ fn full_sync_tolerates_only_unsupported_errors() { } /// Apple's ENOTSUP is 45 (EOPNOTSUPP is 102), and std maps only the latter to -/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. Elsewhere 45 is -/// another error (EL2NSYNC on Linux) and stays a failed save. +/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. On Linux, 45 is +/// EL2NSYNC and stays a failed save. On FreeBSD and other BSDs, 45 is ENOTSUP (the same value as +/// EOPNOTSUPP), so this host's std reports `ErrorKind::Unsupported` and the flush is tolerated +/// even when the `apple` flag is false — which is the real helper's behaviour on those systems. #[cfg(not(target_arch = "wasm32"))] #[test] fn full_sync_tolerates_apple_enotsup() { - use std::io::Error; + use std::io::{Error, ErrorKind}; let enotsup = Error::from_raw_os_error(45); assert!(flush_unsupported_on(&enotsup, true, true), "ENOTSUP on Apple"); - assert!(!flush_unsupported_on(&enotsup, true, false), "45 on other Unix"); - assert!(!flush_unsupported_on(&enotsup, false, false), "45 on Windows"); + let host_maps_45_unsupported = enotsup.kind() == ErrorKind::Unsupported; + assert_eq!(flush_unsupported_on(&enotsup, true, false), host_maps_45_unsupported, "45 on other Unix"); + assert_eq!(flush_unsupported_on(&enotsup, false, false), host_maps_45_unsupported, "45 on Windows"); assert!(flush_unsupported_on(&Error::from_raw_os_error(25), true, true), "ENOTTY on Apple"); assert!(!flush_unsupported_on(&Error::from_raw_os_error(5), true, true), "EIO on Apple"); assert!(!flush_unsupported_on(&Error::from_raw_os_error(28), true, true), "ENOSPC on Apple"); From 1cb02c43e5fe9017c4a27957fbee1ea6f4411fa9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 09:33:55 -0500 Subject: [PATCH 03/10] ci(release): forward ARTCRAFT_SERVICES_DISPATCH_TOKEN secret (#4690) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e09499812d..86c3dbf4a1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,3 +48,4 @@ jobs: AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} From 16f408d5c35ac7e1cb7cce8fd69805c15bdbbee2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 13:17:10 -0500 Subject: [PATCH 04/10] ci(release): publish scheduled nightly prereleases (#4695) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 86c3dbf4a1..c18b13ff42 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,7 +27,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - dry-run: ${{ github.event_name == 'schedule' }} + nightly: ${{ github.event_name == 'schedule' }} app-name: gridcraft app-title: GridCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 0f03eeddd5b7a255801fecf524b6e1794a7d6ec1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 14:45:17 -0500 Subject: [PATCH 05/10] revert: restore scheduled release.yml dry-run on main (#4698) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c18b13ff42..86c3dbf4a1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,7 +27,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - nightly: ${{ github.event_name == 'schedule' }} + dry-run: ${{ github.event_name == 'schedule' }} app-name: gridcraft app-title: GridCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 9bd3b7cf5da67ebce55740bc7844e1c0d18c033a Mon Sep 17 00:00:00 2001 From: Aleksander Helgaker Date: Mon, 23 Nov 2026 23:21:55 +0100 Subject: [PATCH 06/10] Charts: series drawn and saved by their own kind; XLSX groups per drawn kind (groundwork for ODS) (#4142) * Charts: series drawn and saved by their own kind; XLSX groups per drawn kind Chart::series_kind is the one rule for the kind each series is drawn as: in a combo its own kind (the first a column and the rest lines by default; bars stand upright as columns), elsewhere the chart's kind, keeping a line's own markers or a scatter's own lines (same_family). The renderer, legend, data table and trendline eligibility all ask it; chart.set drops the series kinds a new type doesn't draw. The XLSX writer writes one group per drawn kind on each axis (areas, stacked columns kept), axes of the kind those groups need, a one-kind chart's secondary series on their own axes, and a stock group only for 3 or 4 series. The reader keeps each series' markers and lines, treats groups of one family as one chart, takes the primary axes from the value axis on the left or bottom, and orders series by c:order. * XLSX charts: one pie group, one group per type per axis pair, scatter markers kept Review fixes for the per-kind chart groups: - Pies and doughnuts have no axes: series marked secondary stay in the one group, so a combo turned into a doughnut no longer writes two doughnuts. - One group per type on a pair of axes, as Excel keeps them: clustered and stacked columns (lines and stacked lines, areas and stacked areas) share the first one's grouping instead of writing two groups on the same axes. - A markers-only scatter (or bubble) series drawn among lines keeps its markers. - chart-parity.md: the revision row moves under Revision history. * Charts: one grouping per type and axis pair, drawn as saved; combo pies as columns Second review round for the per-kind chart groups: - Chart::series_kind gives the series of one type (columns, lines, areas) on one pair of axes in a combo the first one's grouping, as the XLSX writer saves them, so a stacked column beside clustered ones no longer un-stacks after save and reopen. Chart::series_kinds computes them in one pass. - A combo's pies and doughnuts are drawn as columns (as the renderer does); only a chart without axes ignores secondary flags, so a combo with a secondary pie keeps its primary axes and writes the pie where it is drawn, and a pie + doughnut combo is one column group. - Groups that fit the axes come before groups moved onto them, and each group writes its series in their own order. - The unreachable bubble arm in series_xml is gone. * Charts: combos drawn and saved on category axes; data tables by series_kinds Third review round for the per-kind chart groups: - A combination chart is drawn on category axes, so Chart::series_kind gives its scatter and radar series as lines (a markers-only scatter with markers) and its bubbles as columns, as the renderer draws them; the XLSX writer uses category axes for every combo, so a scatter or bubble series first no longer turns the other series into scatter series. - supports_data_table uses series_kinds (one pass, it runs every frame). - A same-family kind left in an older JSON workbook is drawn, tested and documented rather than migrated: it can't be told from a file's own. * Charts: combo chartex series as columns; empty charts survive XLSX; a new type applies to every series - `combo_series_kind` draws a combo's histogram, waterfall, funnel, treemap, sunburst and box & whisker series as clustered columns, as the XLSX writer already saved them: their grouping, combo-ness and data-table support no longer change on reopening. - The XLSX writer writes one empty group of the chart's kind (a line group for stock) when a chart has no series, so the chart is read back rather than dropped. - The XLSX reader looks the value axes' positions up in a map built once; a file with many chart groups took quadratic time to read. - `chart.set` with a new type (other than a combo) clears every series' own kind, so choosing a type applies it to every series again (a file's markers no longer outlive a type change); setting the type a chart already has drops only the kinds it does not draw. - docs/chart-parity.md: combo scatter series are lines with markers, and only stock series beside stacked lines are still saved stacked but drawn unstacked. * Charts: one model rule reads per-series kinds back; empty charts keep their kind in XLSX - `Chart::set_drawn_kinds` sets a chart's kind and its series' own kinds from the kinds a file draws each series as (one family: the first's kind, a series keeping its own only where it differs; otherwise a combo). The XLSX reader now uses it, so an ODS reader can share the rule instead of copying it. - An empty line group writes `c:marker val="0"` when the chart has no markers, and an empty scatter group `scatterStyle val="marker"`: an empty Line chart no longer reopens with markers, an empty Scatter chart no longer with lines, an empty stock chart as a Line chart. The test now checks the kind read back; the previous commit's test listed Waterfall, which goes through the column writer there and proved nothing (empty chartex charts are still not kept, as before this branch; documented). - `drop_foreign_series_kinds` is removed: since the previous commit, `chart.set` clears every series' kind on a change of type, and the helper only ran when the same type was set again, where `series_kind` already ignores kinds outside the chart's family. - `series_kind`'s doc states the combo conversions and the same-family rule; the combo row in docs/chart-parity.md lists every conversion. * XLSX charts: an empty group sets neither the chart's kind nor its axes The reader took the chart's first kind and its primary axes from the first group even when that group held no series, so a file with an empty bar group before a scatter group read as a scatter chart whose only series was secondary, with the bar group's axis titles. Empty groups are now left out when any group has series, and the axis titles come from the primary pair's axes (found by id, in any order), else the first axis of their kind as before. * XLSX charts: axis titles from shown axes, by the primary pair's kind Corrects the previous commit's axis lookup. When a file's only series sit on a pair whose category axis is deleted, beside an empty group on shown, titled axes, the x title came from the deleted axis (none) instead of the shown one: a shown axis of a kind is now taken before a deleted one. And whether the axes are a scatter's two value axes is now decided by the group on the primary pair, not the first group with series, so a secondary line group listed before a primary scatter no longer gives the y axis the scatter's x title. * Charts: the stacked hairline-bar budget test draws stacked columns Resolved series carry the kind they are drawn as (Chart::series_kind), and the test's data defaulted every series to clustered columns, so after the merge with main it no longer drew a stacked chart and passed without testing stacked spans. Its series are now stacked columns. * Charts: SeriesData::kind says render draws every series by it * XLSX charts: the many-groups test reaches the axis lookup and is timed * chart.addElement: trendlines for every series check their kinds in one pass A combo series' kind looks back for the first series of its group, so asking it per series was quadratic in a chart with many series. The all-series path now uses Chart::series_kinds() once. Test: trendlines_for_every_series_are_checked_in_linear_time (120,000 series: 0.06 s with the fix, 17.8 s without in a debug build). * xlsx: a lone stock series joins the line group on its axes, keeping its grouping A stock series too few for a stock group falls back to a line. It used to be kept in order with the other groups, so when it came first its plain line group took in the stacked lines after it and saved them unstacked. The fallback now joins after the other groups, so an existing line group keeps its grouping; with none, it is still a plain line. Test: a_lone_stock_series_does_not_unstack_the_lines_beside_it. * model: set_drawn_kinds stores each combo series's kind as it is drawn Series of one type on one pair of axes share the first one's grouping (series_kinds draws and every format saves them so), but set_drawn_kinds stored the file's kinds as given: a stacked column after a clustered one on the same axes was kept as stacked while drawn and saved clustered. It now stores the drawn kind; on the other axes a series keeps its own. Test: drawn_kinds_of_one_type_share_a_grouping_per_pair_of_axes. * tests: linear-time chart checks count their work at two sizes instead of timing it `many_groups_are_read_in_linear_time` and `trendlines_for_every_series_are_checked_in_linear_time` asserted a four-second wall-clock bound, which fails on a busy machine and doesn't show how cost grows. Each now counts the steps its code takes, with a counter that exists only in tests, at n and 8n, and asserts the larger run did less than 16 times the smaller one's work (linear is about 8 times, quadratic about 64). The output checks stay. - xlsx: a cfg(test) counter of value axes visited while finding the primary axes. - model: a `work` counter of series a combo chart's kind lookups visit, behind a new `test-support` feature (as gridcraft-xlsx has) so engine tests can read it; engine's dev-dependency enables it. Shipped builds don't have it. Against the quadratic versions (value axes scanned per group; series_kind asked per series) the tests fail with 2,886,000 visits against 45,750 and 2,566,398 against 40,798. --------- Co-authored-by: Claude Opus 5.5 --- crates/chart/src/lib.rs | 6 +- crates/chart/src/render.rs | 14 +- crates/chart/src/render/cartesian.rs | 6 +- crates/chart/src/render/legend.rs | 17 +- crates/chart/src/render/table.rs | 4 +- crates/chart/src/resolve.rs | 28 +- crates/chart/src/tests.rs | 15 +- crates/chart/src/tests/budget.rs | 4 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/extra/chart.rs | 5 +- crates/engine/src/cmd/insert.rs | 68 +++ crates/engine/src/cmd/insert/chart.rs | 10 +- crates/model/Cargo.toml | 5 + crates/model/src/features.rs | 302 ++++++++++++- crates/xlsx/src/chart.rs | 477 +++++++++++++++------ crates/xlsx/src/tests/chart_combo_kinds.rs | 420 ++++++++++++++++++ crates/xlsx/src/tests/fixtures.rs | 11 +- docs/chart-parity.md | 38 +- 18 files changed, 1230 insertions(+), 201 deletions(-) diff --git a/crates/chart/src/lib.rs b/crates/chart/src/lib.rs index f4e2895fe6..9092ef2c3e 100644 --- a/crates/chart/src/lib.rs +++ b/crates/chart/src/lib.rs @@ -26,7 +26,7 @@ use serde::{Deserialize, Serialize}; pub use axis::{Scale, format_number, nice_scale}; pub use raster::rasterize; pub use render::{Swatch, legend_entries, render, supports_trendline}; -pub use resolve::{default_palette, has_volatile_series, resolve, series_color, series_plot_kind}; +pub use resolve::{default_palette, has_volatile_series, resolve, series_color}; pub use sparkline::render_sparkline; /// Straight (non-premultiplied) RGBA colour. @@ -143,7 +143,9 @@ pub struct SeriesData { /// Bubble sizes. pub sizes: Option>>, pub color: Rgba, - /// Per-series kind (combo charts). + /// The kind this series is drawn as. `resolve` sets it from `Chart::series_kind`. `render` + /// reads it for every series of a vertical cartesian or scatter chart, so a hand-built + /// `ChartData` sets it too (`SeriesData::default()` gives `ColumnClustered`). pub kind: ChartKind, /// Plotted against the secondary (right) value axis. pub secondary: bool, diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index c3f284bd98..48259d4c29 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -141,13 +141,20 @@ pub(crate) fn sanitize(d: &ChartData) -> ChartData { .series .iter() .take(MAX_SERIES) - .map(|s| SeriesData { + .enumerate() + .map(|(i, s)| SeriesData { name: s.name.clone(), values: sanitize_vals(&s.values), x: s.x.as_deref().map(sanitize_vals), sizes: s.sizes.as_deref().map(sanitize_vals), color: s.color, - kind: s.kind, + // `resolve` gives each series the kind it is drawn as (`Chart::series_kind`); a + // caller's combo kind is drawn as a combo's defaults: a column first, then lines. + kind: match s.kind { + ChartKind::Combo if i == 0 => ChartKind::ColumnClustered, + ChartKind::Combo => ChartKind::Line, + k => k, + }, secondary: s.secondary, smooth: s.smooth, trendlines: s.trendlines.iter().take(MAX_TRENDLINES).cloned().collect(), @@ -174,7 +181,8 @@ fn needs_sanitizing(d: &ChartData) -> bool { || d.series.len() > MAX_SERIES || d.series.iter().any(|s| { trendlines += s.trendlines.len(); - long(s.values.len()) + s.kind == ChartKind::Combo + || long(s.values.len()) || !s.values.iter().all(is_clean) || s.x.as_ref().is_some_and(|x| long(x.len()) || !x.iter().all(is_clean)) || s.sizes.as_ref().is_some_and(|x| long(x.len()) || !x.iter().all(is_clean)) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 8639409e42..fd4c442248 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -1,5 +1,5 @@ use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range}; -use super::legend::{cat_label, plot_kind}; +use super::legend::cat_label; use super::lines::{decimate_area, draw_markers, draw_runs}; use super::trend::{draw_trend_labels, draw_trendlines, max_backward, max_forward, max_forward_slots, supports_trendline}; use super::{ @@ -292,7 +292,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx if ncat == 0 { return; } - let kinds: Vec = data.series.iter().enumerate().map(|(i, s)| if horizontal { chart.kind } else { plot_kind(chart, s, i) }).collect(); + let kinds: Vec = data.series.iter().map(|s| if horizontal { chart.kind } else { s.kind }).collect(); let fams: Vec = kinds.iter().map(|k| family(*k)).collect(); let any_primary = data.series.iter().any(|s| !s.secondary); let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); @@ -528,7 +528,7 @@ pub(super) fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r, fill: Some(fill), stroke: Some((WHITE, 0.75)) }); } } else { - let lines = chart.kind == ChartKind::ScatterLines || s.kind == ChartKind::ScatterLines; + let lines = s.kind == ChartKind::ScatterLines; if lines { draw_runs(ctx, &px, s.color, 2.0, s.smooth.then_some(plot)); } diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs index a9c7cfac04..d2456ef135 100644 --- a/crates/chart/src/render/legend.rs +++ b/crates/chart/src/render/legend.rs @@ -1,8 +1,8 @@ use super::frame::Bx; use super::trend::supports_trendline; use super::{ - Chart, ChartData, ChartKind, Ctx, DOWN, HAlign, LABEL_SIZE, MAX_CATS, MAX_SERIES, MAX_TRENDLINES, Prim, Rgba, SeriesData, TEXT, Theme, UP, - VAlign, auto_name, series_color, + Chart, ChartData, ChartKind, Ctx, DOWN, HAlign, LABEL_SIZE, MAX_CATS, MAX_SERIES, MAX_TRENDLINES, Prim, Rgba, TEXT, Theme, UP, VAlign, auto_name, + series_color, }; use gridcraft_model::LegendPos; @@ -15,12 +15,6 @@ pub enum Swatch { Marker, } -/// The kind series `i` is drawn as (per-series kinds only apply to combo charts); the same rule -/// as `series_plot_kind`, applied to the already resolved series kind. -pub(super) fn plot_kind(chart: &Chart, s: &SeriesData, i: usize) -> ChartKind { - crate::resolve::plot_kind(chart.kind, Some(s.kind), i) -} - /// Colour of point `j` for charts that colour by point (pie, doughnut, treemap, sunburst). pub(super) fn point_color(data: &ChartData, j: usize) -> Rgba { match (j, data.series.first()) { @@ -61,9 +55,8 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa let series = data.series.iter().take(MAX_SERIES); let mut out: Vec<(String, Rgba, Swatch)> = series .clone() - .enumerate() - .map(|(i, s)| { - let sw = match plot_kind(chart, s, i) { + .map(|s| { + let sw = match s.kind { ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, @@ -73,7 +66,7 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa }) .collect(); // Trendlines follow the series, named "Linear (Sales)" unless given a name. - for (_, s) in series.enumerate().filter(|(i, s)| supports_trendline(plot_kind(chart, s, *i))) { + for s in series.filter(|s| supports_trendline(s.kind)) { for t in s.trendlines.iter().take(MAX_TRENDLINES) { out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line)); } diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index 4f641afd25..9047e0c31e 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -1,7 +1,7 @@ //! The chart data table uses the same primitives as the plot, including in print/PDF output. use super::frame::{Bx, CatAxis, level_groups}; -use super::legend::{Swatch, cat_label, draw_swatch, plot_kind}; +use super::legend::{Swatch, cat_label, draw_swatch}; use super::{AXIS, Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, TEXT, VAlign}; pub(super) struct Layout { @@ -70,7 +70,7 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay let y = top + (layout.headers as f32 + i as f32 + 0.5) * layout.row_height; let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; if settings.show_keys { - let swatch = match plot_kind(chart, series, i) { + let swatch = match series.kind { ChartKind::Line | ChartKind::LineStacked => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, _ => Swatch::Box, diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index e7663e0d9b..5852f6c895 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -448,32 +448,6 @@ fn series_name(wb: &Workbook, sheet: usize, name: &str) -> String { t.to_string() } -pub(crate) fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { - match (chart_kind, series_kind) { - (ChartKind::Combo, Some(k)) if k != ChartKind::Combo => k, - (ChartKind::Combo, _) => { - if i == 0 { - ChartKind::ColumnClustered - } else { - ChartKind::Line - } - } - (_, Some(k)) if k != ChartKind::Combo => k, - (k, _) => k, - } -} - -/// The kind series `i` is drawn as: its own kind in a combo chart (first series a column, the -/// rest lines when it has none), else the chart's. The one rule shared by resolving and drawing. -pub(crate) fn plot_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { - if chart_kind == ChartKind::Combo { effective_kind(chart_kind, series_kind, i) } else { chart_kind } -} - -/// The kind series `i` of `chart` is drawn as: its own kind in a combo chart, else the chart's. -pub fn series_plot_kind(chart: &Chart, i: usize) -> ChartKind { - plot_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) -} - /// Evaluates a chart's series formulas: names, values, categories (default "1", "2", …), X /// values (scatter/bubble), bubble sizes, number formats and colours (explicit, else the /// default palette derived from the workbook theme accents). @@ -489,7 +463,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData { let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1)); let color = s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i)); - let kind = effective_kind(chart.kind, s.kind, i); + let kind = chart.series_kind(i); let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) { // X values with text in them (labels) are ignored: the points are numbered 1..n. (Some(f), true) => { diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index a6d8453875..aa261ab36e 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1421,21 +1421,22 @@ fn area_charts_draw_source_value_labels_only_when_enabled() { #[test] fn drawing_and_resolving_agree_on_the_combo_plot_kind() { - // Resolved series carry `effective_kind`; drawing re-derives the kind from it. Both paths - // must give the same kind for every chart kind, series kind (or none) and series index. + // Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind, + // series kind (or none) and series index it is never a combo, and outside a combo it is the + // chart's kind or one of its family. + let wb = Workbook::new(); let series_kinds = std::iter::once(None).chain(ALL_KINDS.iter().map(|k| Some(*k))); for ck in ALL_KINDS { for sk in series_kinds.clone() { for i in 0..3 { let mut c = chart(ck); c.series = (0..3).map(|j| Series { kind: if j == i { sk } else { None }, ..Default::default() }).collect(); - let from_chart = series_plot_kind(&c, i); - let resolved = crate::resolve::effective_kind(ck, sk, i); - assert_eq!(crate::resolve::plot_kind(ck, Some(resolved), i), from_chart, "{ck:?} {sk:?} {i}"); + let resolved: Vec = resolve(&wb, 0, &c).series.iter().map(|s| s.kind).collect(); + assert_eq!(resolved, c.series_kinds(), "{ck:?} {sk:?} {i}"); if ck != ChartKind::Combo { - assert_eq!(from_chart, ck); + assert!(gridcraft_model::same_family(ck, resolved[i]), "{ck:?} {sk:?} {i}"); } else { - assert_ne!(from_chart, ChartKind::Combo); + assert_ne!(resolved[i], ChartKind::Combo); } } } diff --git a/crates/chart/src/tests/budget.rs b/crates/chart/src/tests/budget.rs index fad349ba6d..cc779f13be 100644 --- a/crates/chart/src/tests/budget.rs +++ b/crates/chart/src/tests/budget.rs @@ -166,6 +166,10 @@ fn stacked_hairline_bars_do_not_fill_the_gap_between_disjoint_spans() { c.data_labels = false; c.legend = LegendPos::None; let mut d = data_of(2, 20_000); + // Resolved series carry the kind they are drawn as (`Chart::series_kind`): stacked columns. + for s in &mut d.series { + s.kind = ChartKind::ColumnStacked; + } for v in d.series[0].values.iter_mut() { *v = Some(100.0); } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f06e3b8d6c..21f6b6dcc1 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -31,4 +31,5 @@ unicode-segmentation = "=1.13.3" [dev-dependencies] gridcraft-xlsx = { workspace = true, features = ["test-support"] } +gridcraft-model = { workspace = true, features = ["test-support"] } zip = { workspace = true } diff --git a/crates/engine/src/cmd/extra/chart.rs b/crates/engine/src/cmd/extra/chart.rs index b6ed184edf..42ed5af75a 100644 --- a/crates/engine/src/cmd/extra/chart.rs +++ b/crates/engine/src/cmd/extra/chart.rs @@ -69,8 +69,11 @@ pub(super) fn add_element(s: &mut Session, p: &Json) -> Result { return Ok(()); } let t = trendline_param(p)?; + // Every series' kind in one pass: a combo series' kind looks back for its group's + // first series, so asking per series is quadratic in a chart with many. + let kinds = c.series_kinds(); let eligible: Vec = - targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect(); + targets.into_iter().filter(|i| kinds.get(*i).is_some_and(|k| gridcraft_chart::supports_trendline(*k))).collect(); if eligible.is_empty() { return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series")); } diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 686fca6f5c..41310782cb 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -337,6 +337,74 @@ mod tests { assert_eq!(serde_json::from_value::(json).unwrap().data_table, None); } + #[test] + fn chart_type_change_drops_series_kinds_it_does_not_draw() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "A", "B"], ["Q1", 10, 1], ["Q2", 20, 2]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "combo"})).unwrap(); + let chart = |s: &Session| s.active().unwrap().wb.active().unwrap().charts[0].clone(); + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + let active = wb.active_sheet(); + if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) { + c.series[0].kind = Some(ChartKind::Area); + c.series[1].kind = Some(ChartKind::LineMarkers); + } + // A new type applies to every series: neither the area nor the markers stay. + s.execute("chart.set", json!({"type": "line"})).unwrap(); + let c = chart(&s); + assert_eq!(c.series.iter().map(|x| x.kind).collect::>(), vec![None, None]); + assert_eq!((c.series_kind(0), c.series_kind(1)), (ChartKind::Line, ChartKind::Line)); + // Setting the type a chart already has keeps a series' own markers (a file's). + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) { + c.series[1].kind = Some(ChartKind::LineMarkers); + } + s.execute("chart.set", json!({"type": "line", "subtype": ""})).unwrap(); + assert_eq!(chart(&s).series_kinds(), vec![ChartKind::Line, ChartKind::LineMarkers]); + // Trendlines go by the kind each series is drawn as. + s.execute("chart.set", json!({"type": "pie"})).unwrap(); + assert!(s.execute("chart.addElement", json!({"element": "trendline"})).is_err()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(chart(&s).series[1].kind, Some(ChartKind::LineMarkers)); + } + + /// Adding a trendline to every series of a combo chart works out the series' kinds in one + /// pass, however many series it holds (a stored chart isn't held to the renderer's limit): + /// eight times the series is about eight times the work, not sixty-four. + #[test] + fn trendlines_for_every_series_are_checked_in_linear_time() { + let visits = |n: usize| { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "A"], ["Q1", 10], ["Q2", 20]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "type": "combo"})).unwrap(); + // Line series, then as many column series: asked one at a time, each column series + // looks back past every line series for the first column series of its group. + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + let active = wb.active_sheet(); + if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) { + let one = c.series[0].clone(); + c.series = (0..2 * n) + .map(|i| { + let mut se = one.clone(); + se.kind = Some(if i < n { ChartKind::Line } else { ChartKind::ColumnClustered }); + se + }) + .collect(); + } + gridcraft_model::features::work::take_series_visits(); + s.execute("chart.addElement", json!({"element": "trendline"})).unwrap(); + let visits = gridcraft_model::features::work::take_series_visits(); + let c = s.active().unwrap().wb.active().unwrap().charts[0].clone(); + assert!(c.series.iter().all(|se| se.trendlines.len() == 1)); + visits + }; + let (small, large) = (visits(200), visits(1_600)); + assert!(small >= 400, "every series' kind is worked out: {small}"); + assert!(large < 16 * small, "eight times the series took {large} visits against {small}"); + } + #[test] fn chart_data_table_refuses_unsupported_types_without_changing_history() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/insert/chart.rs b/crates/engine/src/cmd/insert/chart.rs index 69425ca794..66c99414f8 100644 --- a/crates/engine/src/cmd/insert/chart.rs +++ b/crates/engine/src/cmd/insert/chart.rs @@ -330,7 +330,15 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(si)?; let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) }; if let Some(t) = str_param(p, "type") { - c.kind = chart_kind(t, str_param(p, "subtype").unwrap_or("")); + let kind = chart_kind(t, str_param(p, "subtype").unwrap_or("")); + // A new type (other than a combo) applies to every series, as choosing it did before + // series kept their own: their markers or lines from a file go with the old type. + if kind != c.kind && kind != ChartKind::Combo { + for series in &mut c.series { + series.kind = None; + } + } + c.kind = kind; if !c.supports_data_table() { c.data_table = None; } diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index ff15c67953..d658ae739e 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -8,6 +8,11 @@ description = "GridCraft document model: workbooks, sheets, cells, styles, table [lints] workspace = true +[features] +# Counts work for other crates' growth tests (a dev-dependency feature; never enabled in a +# shipped build). +test-support = [] + [dependencies] gridcraft-core = { workspace = true } sha2 = { workspace = true } diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index d8bad07bc5..bba75dce29 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -620,7 +620,155 @@ pub struct Chart { pub pivot: Option, } +/// Whether a series of kind `b` can be drawn in a chart of kind `a` without making it a combo: +/// the same kind, or a line with or without markers, or a scatter with or without lines. +pub fn same_family(a: ChartKind, b: ChartKind) -> bool { + use ChartKind::*; + a == b || matches!((a, b), (Line | LineMarkers, Line | LineMarkers) | (Scatter | ScatterLines, Scatter | ScatterLines)) +} + +/// The kind a combo chart's series `i` with its own kind `own` is drawn as. +fn combo_series_kind(own: Option, i: usize) -> ChartKind { + match own { + // A combination chart's bars stand upright: its categories run across. + Some(ChartKind::BarClustered) => ChartKind::ColumnClustered, + Some(ChartKind::BarStacked) => ChartKind::ColumnStacked, + Some(ChartKind::BarStacked100) => ChartKind::ColumnStacked100, + // A combination chart is drawn on category axes: its pies, doughnuts, bubbles and chartex + // kinds (histogram, waterfall, funnel, treemap, sunburst, box & whisker) as clustered + // columns, its scatter and radar series as lines (a markers-only scatter with markers). + Some( + ChartKind::Pie + | ChartKind::Doughnut + | ChartKind::Bubble + | ChartKind::Histogram + | ChartKind::Waterfall + | ChartKind::Funnel + | ChartKind::Treemap + | ChartKind::Sunburst + | ChartKind::BoxWhisker, + ) => ChartKind::ColumnClustered, + Some(ChartKind::Scatter) => ChartKind::LineMarkers, + Some(ChartKind::ScatterLines | ChartKind::Radar) => ChartKind::Line, + Some(k) if k != ChartKind::Combo => k, + _ if i == 0 => ChartKind::ColumnClustered, + _ => ChartKind::Line, + } +} + +/// The types whose series on one pair of axes share one grouping (clustered or stacked). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Grouped { + Column, + Line, + Area, +} + +fn grouped(k: ChartKind) -> Option { + use ChartKind::*; + match k { + ColumnClustered | ColumnStacked | ColumnStacked100 => Some(Grouped::Column), + Line | LineMarkers | LineStacked => Some(Grouped::Line), + Area | AreaStacked | AreaStacked100 => Some(Grouped::Area), + _ => None, + } +} + +/// Kind `k` drawn in the grouping of `first`, the first series of its type on its axes: columns +/// and areas take its kind; a line is stacked when it is, and unstacked (keeping its own +/// markers) when it isn't. +fn regroup(k: ChartKind, first: ChartKind) -> ChartKind { + match (grouped(k), first) { + (Some(Grouped::Line), ChartKind::LineStacked) => ChartKind::LineStacked, + (Some(Grouped::Line), _) if k == ChartKind::LineStacked => ChartKind::Line, + (Some(Grouped::Line), _) => k, + _ => first, + } +} + impl Chart { + /// The kind series `i` is drawn as, and saved as (the one rule the renderer and every file + /// format share). + /// + /// In a combo chart: the series' own kind, else a column for the first series and a line + /// for the rest. A combo is drawn on category axes, so bars stand upright as columns; pies, + /// doughnuts, bubbles and chartex kinds are clustered columns; scatter series are lines with + /// markers, and scatter-with-lines and radar series plain lines. The series of one type on + /// one pair of axes share the first one's grouping (as Excel keeps them): a stacked column + /// after a clustered one is clustered. + /// + /// In any other chart: the chart's kind, or the series' own kind where it is of the same + /// family ([`same_family`]: a line's own markers, a scatter's own lines). + pub fn series_kind(&self, i: usize) -> ChartKind { + let own = self.series.get(i).and_then(|s| s.kind).filter(|k| *k != ChartKind::Combo); + match (self.kind, own) { + (ChartKind::Combo, own) => { + let k = combo_series_kind(own, i); + let Some(t) = grouped(k) else { return k }; + let secondary = self.series.get(i).is_some_and(|s| s.secondary); + let first = self.series.iter().enumerate().take(i).find_map(|(j, s)| { + #[cfg(any(test, feature = "test-support"))] + work::visit(); + let kj = combo_series_kind(s.kind, j); + (s.secondary == secondary && grouped(kj) == Some(t)).then_some(kj) + }); + first.map_or(k, |f| regroup(k, f)) + } + (k, Some(own)) if same_family(k, own) => own, + (k, _) => k, + } + } + + /// The kind every series is drawn as ([`Chart::series_kind`]), in one pass. + pub fn series_kinds(&self) -> Vec { + if self.kind != ChartKind::Combo { + return (0..self.series.len()).map(|i| self.series_kind(i)).collect(); + } + let mut firsts: Vec<(Grouped, bool, ChartKind)> = Vec::new(); + self.series + .iter() + .enumerate() + .map(|(i, s)| { + #[cfg(any(test, feature = "test-support"))] + work::visit(); + let k = combo_series_kind(s.kind, i); + let Some(t) = grouped(k) else { return k }; + match firsts.iter().find(|(ft, sec, _)| *ft == t && *sec == s.secondary) { + Some((_, _, f)) => regroup(k, *f), + None => { + firsts.push((t, s.secondary, k)); + k + } + } + }) + .collect() + } + + /// Sets the chart's kind and each series' own kind from the kinds a file draws its series + /// as (XLSX chart groups, ODS `chart:class`), one per series in order; `empty` is the + /// chart's kind when it has no series. Series of one family make a chart of the first's + /// kind, a series keeping its own kind only where it differs (a line's own markers, a + /// scatter's own lines); series of other families make a combination chart, every series + /// keeping its kind, except that the series of one type on one pair of axes share the first + /// one's grouping, as [`Chart::series_kinds`] draws and every format saves them (a stacked + /// column after a clustered one on the same axes is kept clustered; on the other axes it + /// stays stacked). Each series' own kind is then the kind it is drawn as. Set the series' + /// axes (`secondary`) first. + pub fn set_drawn_kinds(&mut self, drawn: &[ChartKind], empty: ChartKind) { + let first = drawn.first().copied().unwrap_or(empty); + let combo = drawn.iter().any(|k| !same_family(*k, first)); + self.kind = if combo { ChartKind::Combo } else { first }; + for (s, k) in self.series.iter_mut().zip(drawn) { + s.kind = (combo || *k != first).then_some(*k); + } + if combo { + let kinds = self.series_kinds(); + for (s, k) in self.series.iter_mut().zip(kinds) { + s.kind = Some(k); + } + } + } + /// Data tables belong to category-axis column, bar, line and area charts. pub fn supports_data_table(&self) -> bool { let eligible = |kind| { @@ -640,7 +788,7 @@ impl Chart { | ChartKind::AreaStacked100 ) }; - eligible(self.kind) || (self.kind == ChartKind::Combo && self.series.iter().all(|s| eligible(s.kind.unwrap_or(ChartKind::Line)))) + eligible(self.kind) || (self.kind == ChartKind::Combo && self.series_kinds().into_iter().all(eligible)) } } @@ -1120,6 +1268,158 @@ pub struct Slicer { pub columns: u32, } +/// Work counters for growth tests here and in other crates (`test-support`; never in a shipped +/// build): a test compares the counts at two input sizes instead of timing the work. +#[cfg(any(test, feature = "test-support"))] +pub mod work { + thread_local! { + /// Series a combo chart's kind lookups have visited on this thread. + static SERIES_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(crate) fn visit() { + SERIES_VISITS.with(|n| n.set(n.get().saturating_add(1))); + } + + /// The series visited since the last call, and starts counting again. + pub fn take_series_visits() -> usize { + SERIES_VISITS.with(|n| n.replace(0)) + } +} + +#[cfg(test)] +mod series_kind_tests { + use super::{Chart, ChartKind, Series}; + + fn chart(kind: ChartKind, own: &[Option]) -> Chart { + Chart { + id: 1, + kind, + anchor: Default::default(), + title: None, + series: own.iter().map(|k| Series { kind: *k, ..Series::default() }).collect(), + legend: Default::default(), + data_labels: false, + data_table: None, + gridlines: true, + style: 2, + hole_size: 75, + first_slice_angle: 0, + x_title: None, + y_title: None, + source: None, + by_rows: false, + pivot: None, + } + } + + fn drawn(c: &Chart) -> Vec { + (0..c.series.len()).map(|i| c.series_kind(i)).collect() + } + + #[test] + fn combo_series_default_to_a_column_then_lines_and_bars_and_pies_stand_upright() { + use ChartKind::*; + let c = chart(Combo, &[None, None, Some(Combo), Some(Area), Some(BarClustered), Some(Doughnut)]); + assert_eq!(drawn(&c), vec![ColumnClustered, Line, Line, Area, ColumnClustered, ColumnClustered]); + for (bar, column) in [(BarStacked, ColumnStacked), (BarStacked100, ColumnStacked100)] { + assert_eq!(drawn(&chart(Combo, &[Some(bar), Some(Line)])), vec![column, Line]); + } + // On a combo's category axes scatter and radar series are lines (a markers-only scatter + // keeps its markers) and bubbles are columns. + let c = chart(Combo, &[Some(Scatter), Some(ScatterLines), Some(Radar), Some(Bubble)]); + assert_eq!(drawn(&c), vec![LineMarkers, Line, Line, ColumnClustered]); + // Out of range: the default for that position, never a panic. + assert_eq!(c.series_kind(usize::MAX), Line); + } + + #[test] + fn outside_a_combo_a_series_keeps_only_its_own_markers_or_lines() { + use ChartKind::*; + assert_eq!(drawn(&chart(Line, &[None, Some(LineMarkers), Some(Area)])), vec![Line, LineMarkers, Line]); + assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter), Some(Line)])), vec![Scatter, ScatterLines]); + assert_eq!(drawn(&chart(ColumnClustered, &[Some(Line)])), vec![ColumnClustered]); + } + + #[test] + fn combo_series_of_one_type_on_one_axis_share_the_first_grouping() { + use ChartKind::*; + let c = chart( + Combo, + &[Some(ColumnStacked), Some(ColumnClustered), Some(Pie), Some(LineStacked), Some(LineMarkers), Some(Area), Some(AreaStacked100)], + ); + assert_eq!(drawn(&c), vec![ColumnStacked, ColumnStacked, ColumnStacked, LineStacked, LineStacked, Area, Area]); + assert_eq!(c.series_kinds(), drawn(&c)); + // An unstacked line keeps its own markers; a stacked one after it is unstacked. + let c = chart(Combo, &[Some(Line), Some(LineMarkers), Some(LineStacked)]); + assert_eq!(drawn(&c), vec![Line, LineMarkers, Line]); + // Each pair of axes has its own first. + let mut c = chart(Combo, &[Some(ColumnClustered), Some(ColumnStacked)]); + c.series[1].secondary = true; + assert_eq!(drawn(&c), vec![ColumnClustered, ColumnStacked]); + assert_eq!(c.series_kinds(), drawn(&c)); + } + + /// A series' own markers or lines outside a combo are honoured wherever they come from: an + /// XLSX file's per-series markers, or a kind left in an older GridCraft JSON workbook by a + /// type change made before `chart.set` cleared series kinds on a change of type (not + /// migrated: the two can't be told apart). + /// A file's per-series kinds make a chart of one family, or a combo, that draws them so. + #[test] + fn drawn_kinds_set_the_chart_and_its_series() { + use ChartKind::*; + let mut c = chart(ColumnClustered, &[None, None, None]); + c.set_drawn_kinds(&[Line, LineMarkers, Line], ColumnClustered); + assert_eq!((c.kind, c.series.iter().map(|s| s.kind).collect::>()), (Line, vec![None, Some(LineMarkers), None])); + assert_eq!(c.series_kinds(), vec![Line, LineMarkers, Line]); + c.set_drawn_kinds(&[ColumnStacked, Line, Area], ColumnClustered); + assert_eq!(c.kind, Combo); + assert_eq!(c.series_kinds(), vec![ColumnStacked, Line, Area]); + let mut empty = chart(ColumnClustered, &[]); + empty.set_drawn_kinds(&[], Radar); + assert_eq!(empty.kind, Radar); + } + + /// Series of one type on one pair of axes keep the first one's grouping, so the kinds a + /// file gives them are stored as they are drawn and saved; on the other axes they keep their + /// own. + #[test] + fn drawn_kinds_of_one_type_share_a_grouping_per_pair_of_axes() { + use ChartKind::*; + let mut c = chart(ColumnClustered, &[None, None, None, None]); + c.set_drawn_kinds(&[ColumnClustered, ColumnStacked, ColumnStacked, Line], ColumnClustered); + assert_eq!( + c.series.iter().map(|s| s.kind).collect::>(), + vec![Some(ColumnClustered); 3].into_iter().chain([Some(Line)]).collect::>() + ); + assert_eq!(c.series.iter().map(|s| s.kind).collect::>(), c.series_kinds().into_iter().map(Some).collect::>()); + let mut c = chart(ColumnClustered, &[None, None, None, None]); + c.series[1].secondary = true; + c.series[2].secondary = true; + c.set_drawn_kinds(&[ColumnClustered, ColumnStacked, ColumnStacked, Line], ColumnClustered); + assert_eq!(c.series_kinds(), vec![ColumnClustered, ColumnStacked, ColumnStacked, Line]); + assert_eq!(c.series.iter().map(|s| s.kind).collect::>(), c.series_kinds().into_iter().map(Some).collect::>()); + } + + #[test] + fn a_leftover_kind_in_the_same_family_is_drawn() { + use ChartKind::*; + let json = serde_json::to_value(chart(Line, &[None, Some(LineMarkers)])).unwrap(); + let c: Chart = serde_json::from_value(json).unwrap(); + assert_eq!(drawn(&c), vec![Line, LineMarkers]); + assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter)])), vec![Scatter]); + } + + #[test] + fn a_combo_supports_a_data_table_by_its_drawn_kinds() { + use ChartKind::*; + assert!(chart(Combo, &[None, None]).supports_data_table()); + // Its scatter series are drawn as lines on its category axes; stock series have no table. + assert!(chart(Combo, &[None, Some(Scatter)]).supports_data_table()); + assert!(!chart(Combo, &[None, Some(Stock)]).supports_data_table()); + } +} + #[cfg(test)] mod trendline_forecast_tests { use super::Trendline; diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index eb1d22087f..f8511d6232 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -1,6 +1,7 @@ //! DrawingML charts (`xl/charts/chartN.xml`): reading the common 2-D/3-D chart groups into the //! model, and writing model charts (with cached series values) from scratch. +use std::collections::HashMap; use std::fmt::Write as _; use craft_drawingml::chart::{Chart as DmlChart, ChartType, Trendline as DmlTrendline, TrendlineType}; @@ -196,34 +197,176 @@ const DASHES: [(LineDash, &str); 11] = [ const EMU_PER_PT: f64 = 12_700.0; +fn group_kind(g: &El) -> Option { + let grouping = g.child_val("grouping").unwrap_or("standard"); + let stacked = grouping == "stacked"; + let pct = grouping == "percentStacked"; + Some(match g.name.as_str() { + "barChart" | "bar3DChart" => { + let bar = g.child_val("barDir") == Some("bar"); + match (bar, stacked, pct) { + (false, true, _) => ChartKind::ColumnStacked, + (false, _, true) => ChartKind::ColumnStacked100, + (false, _, _) => ChartKind::ColumnClustered, + (true, true, _) => ChartKind::BarStacked, + (true, _, true) => ChartKind::BarStacked100, + (true, _, _) => ChartKind::BarClustered, + } + } + "lineChart" | "line3DChart" => { + if stacked || pct { + ChartKind::LineStacked + } else { + // The group's kind is its first series' (each series may differ; see + // `series_kind_in`). + match g.kids("ser").next() { + Some(first) => series_kind_in(g, ChartKind::LineMarkers, first), + None if g.child_val("marker").is_some_and(|v| v == "0" || v == "false") => ChartKind::Line, + None => ChartKind::LineMarkers, + } + } + } + "pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie, + "doughnutChart" => ChartKind::Doughnut, + "areaChart" | "area3DChart" => { + if pct { + ChartKind::AreaStacked100 + } else if stacked { + ChartKind::AreaStacked + } else { + ChartKind::Area + } + } + "scatterChart" => match g.kids("ser").next() { + _ if g.child_val("scatterStyle") == Some("marker") => ChartKind::Scatter, + Some(first) => series_kind_in(g, ChartKind::ScatterLines, first), + None => ChartKind::ScatterLines, + }, + "bubbleChart" => ChartKind::Bubble, + "radarChart" => ChartKind::Radar, + "stockChart" => ChartKind::Stock, + _ => return None, + }) +} + +/// The kind series `s` of group `g` (of kind `k`) is drawn as: in a line group its own markers +/// (none when it says so), in a scatter group its own lines; otherwise the group's. +fn series_kind_in(g: &El, k: ChartKind, s: &El) -> ChartKind { + match k { + ChartKind::Line | ChartKind::LineMarkers => { + let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); + let none = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + if group_markers && !none { ChartKind::LineMarkers } else { ChartKind::Line } + } + ChartKind::Scatter | ChartKind::ScatterLines if g.child_val("scatterStyle") != Some("marker") => { + if s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some()) { ChartKind::Scatter } else { ChartKind::ScatterLines } + } + k => k, + } +} + +fn rich_title(t: &El) -> Option { + let tx = t.child("tx")?; + if let Some(rich) = tx.child("rich") { + let paras: Vec = + rich.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::()).collect(); + let s = paras.join("\n"); + return if s.is_empty() { None } else { Some(s) }; + } + if let Some(sr) = tx.child("strRef") { + if let Some(v) = sr.path(&["strCache", "pt", "v"]) { + return Some(v.text.clone()); + } + return sr.child("f").map(|f| f.text.trim().to_string()); + } + None +} + +/// The text of an axis title (`c:title`): its rich text or cached reference, else Excel's default. +fn axis_title(t: &El) -> String { + rich_title(t).unwrap_or_else(|| "Axis Title".into()) +} + +// Value axes looked at (and looked up) while finding a chart's primary axes, so a test can check +// the work grows with the file, not with its square. +#[cfg(test)] +thread_local! { + pub(crate) static VAL_AXIS_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { let plot = root.and_then(|r| r.path(&["chart", "plotArea"])); let groups: Vec<&El> = plot.map(|p| p.children.iter().filter(|g| g.name.ends_with("Chart")).collect()).unwrap_or_default(); fn ax_ids(g: &El) -> Vec<&str> { g.kids("axId").filter_map(|a| a.attr("val")).collect() } - let first_axes = groups.first().map(|g| ax_ids(g)).unwrap_or_default(); - let ser_els: Vec<(&El, bool)> = groups + // An empty group draws nothing: the chart's kind and axes come from the groups with series + // (a chart without series from its first group). + let kinded: Vec<(&El, ChartKind)> = groups.iter().filter_map(|g| group_kind(g).map(|k| (*g, k))).collect(); + let with_series = kinded.iter().any(|(g, _)| g.child("ser").is_some()); + let drawing: Vec<(&El, ChartKind)> = kinded.iter().copied().filter(|(g, _)| !with_series || g.child("ser").is_some()).collect(); + let first_kind = drawing.first().map_or_else(|| map_chart_type(dc.kind, plot), |(_, k)| *k); + // The primary axes are the pair whose value axis sits left or bottom (a secondary pair is on + // the right or top), else the first group's; series on other axes are secondary. + let mut val_sides: HashMap<&str, &str> = HashMap::new(); + for a in plot.into_iter().flat_map(|p| p.kids("valAx")) { + #[cfg(test)] + VAL_AXIS_VISITS.with(|n| n.set(n.get().saturating_add(1))); + if let (Some(id), Some(pos)) = (a.child_val("axId"), a.child_val("axPos")) { + val_sides.entry(id).or_insert(pos); + } + } + let pairs: Vec> = drawing.iter().map(|(g, _)| ax_ids(g)).collect(); + let primary_axes: Vec<&str> = pairs .iter() - .enumerate() - .flat_map(|(gi, g)| { - let sec = gi > 0 && ax_ids(g) != first_axes; - g.kids("ser").map(move |s| (s, sec)) + .find(|ids| { + #[cfg(test)] + VAL_AXIS_VISITS.with(|n| n.set(n.get().saturating_add(1))); + ids.get(1).is_some_and(|id| matches!(val_sides.get(id).copied(), Some("l" | "b"))) + }) + .or_else(|| pairs.iter().find(|ids| !ids.is_empty())) + .cloned() + .unwrap_or_default(); + // The axis titles are the primary pair's (an axis of another pair, or of an empty group, holds + // another scale's titles), else the first of their kind in the file; a shown axis before a + // deleted one. + let primary = |a: &El| a.child_val("axId").is_some_and(|id| primary_axes.contains(&id)); + let shown = |a: &El| !a.child("delete").is_some_and(|c| c.flag("val", true)); + let first_of = |tags: &[&str], pos: &[&str]| -> Option<&El> { + let fits = |a: &&El| tags.contains(&a.name.as_str()) && (pos.is_empty() || a.child_val("axPos").is_some_and(|p| pos.contains(&p))); + let axes = plot.into_iter().flat_map(|p| p.children.iter()).filter(fits); + let ranked: [&dyn Fn(&El) -> bool; 4] = [&|a| primary(a) && shown(a), &shown, &primary, &|_| true]; + ranked.into_iter().find_map(|r| axes.clone().find(|a| r(a))) + }; + // The primary pair's group says whether its axes are both value axes (a scatter's). + let primary_kind = drawing.iter().zip(&pairs).find(|(_, ids)| **ids == primary_axes).map_or(first_kind, |((_, k), _)| *k); + let (x_ax, y_ax) = if matches!(primary_kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble) { + (first_of(&["valAx"], &["b", "t"]), first_of(&["valAx"], &["l", "r"])) + } else { + (first_of(&["catAx", "dateAx"], &[]), first_of(&["valAx"], &[])) + }; + let title_of = |a: Option<&El>| a.and_then(|a| a.child("title")).map(axis_title); + let axis_titles = if plot.is_some() { (title_of(x_ax), title_of(y_ax)) } else { dc.axis_titles.clone() }; + // Each series element with its axes and the kind its group draws it as (a line's markers and + // a scatter's lines are the series' own), in the order the shared reader lists them. + let ser_els: Vec<(&El, bool, ChartKind)> = groups + .iter() + .flat_map(|g| { + let ids = ax_ids(g); + let sec = !ids.is_empty() && ids != primary_axes; + let k = group_kind(g); + g.kids("ser").map(move |s| (s, sec, k.map_or(first_kind, |k| series_kind_in(g, k, s)))) }) .collect(); - let multi_axis = ser_els.iter().any(|(_, sec)| *sec); - let is_combo = dc.kind == ChartType::Combo || multi_axis; - let base_kind = map_chart_type(dc.kind, plot); - let kind = if is_combo { ChartKind::Combo } else { base_kind }; let series_labels = dc.series.iter().any(|s| s.data_labels == Some(true)); let series = dc .series .into_iter() .enumerate() .map(|(i, s)| { - let (sel, fallback_sec) = match ser_els.get(i).copied() { - Some((el, sec)) => (Some(el), sec), - None => (None, false), + let (sel, sec, drawn) = match ser_els.get(i).copied() { + Some((el, sec, k)) => (Some(el), sec, k), + None => (None, s.secondary_axis, s.kind.map_or(first_kind, |k| map_chart_type(k, plot))), }; let color = s .fill @@ -243,7 +386,7 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { .into_iter() .flat_map(|e| e.kids("trendline").take(16)) .filter(|e| e.child("trendlineType").and_then(|c| c.attr("val")).and_then(TrendlineType::from_xml).is_some()); - Series { + let series = Series { name: s.refs.name.as_deref().map(chart_ref_from_file).or_else(|| (!s.name.is_empty()).then_some(s.name)), categories: s .refs @@ -260,20 +403,22 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { .unwrap_or_default(), bubble_sizes: s.refs.sizes.as_deref().map(chart_ref_from_file).or_else(|| literal_array(sel.and_then(|e| e.child("bubbleSize")))), color, - secondary: is_combo && (s.secondary_axis || fallback_sec), - kind: if dc.kind == ChartType::Combo { - s.kind.map(|k| map_chart_type(k, plot)) - } else if multi_axis { - Some(s.kind.map(|k| map_chart_type(k, plot)).unwrap_or(base_kind)) - } else { - None - }, + secondary: sec, + kind: None, quartiles: Default::default(), smooth: sel.map_or(s.smooth, |e| e.child("smooth").is_some_and(|c| c.flag("val", true))), trendlines: s.trendlines.iter().map(|t| map_trendline(t, trendline_els.next())).collect(), - } + }; + (series, drawn, sel) }) - .collect(); + .collect::>(); + // Series in the order the file gives them (`c:order`), whichever group holds them. + let order = |e: Option<&El>| e.and_then(|s| s.child_val("order")).and_then(|v| v.parse::().ok()); + let mut series = series; + if series.iter().all(|(_, _, e)| order(*e).is_some()) { + series.sort_by_key(|(_, _, e)| order(*e)); + } + let (series, drawn): (Vec, Vec) = series.into_iter().map(|(s, k, _)| (s, k)).unzip(); let legend = match dc.legend.as_deref() { None => LegendPos::None, Some("b") => LegendPos::Bottom, @@ -283,9 +428,9 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { }; let hole_size = if plot.is_some_and(|p| p.child("doughnutChart").is_some()) { (dc.hole_size * 100.0).round().clamp(10.0, 90.0) as u8 } else { 75 }; - Chart { + let mut ch = Chart { id: 0, - kind, + kind: first_kind, anchor: Default::default(), title: dc.title, series, @@ -301,12 +446,15 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { style: dc.style, hole_size, first_slice_angle: dc.first_slice_angle, - x_title: dc.axis_titles.0, - y_title: dc.axis_titles.1, + x_title: axis_titles.0, + y_title: axis_titles.1, source: None, by_rows: false, pivot: dc.pivot_source.as_deref().map(strip_book).filter(|n| !n.is_empty()).map(str::to_string), - } + }; + // Series of one family are one chart; series of other families make a combination chart. + ch.set_drawn_kinds(&drawn, first_kind); + ch } pub fn read_chart(root: &El) -> Option { @@ -330,6 +478,45 @@ enum G { Stock, } +/// The kind of axes a group is drawn on. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Axes { + /// None: pie and doughnut. + None, + /// Categories across, values up: columns, lines, areas, stock, radar. + Category, + /// Categories down, values across: horizontal bars. + Horizontal, + /// Values both ways: scatter and bubble. + Values, +} + +fn axes_of(g: G) -> Axes { + match g { + G::Pie | G::Doughnut => Axes::None, + G::Bar { bar: true, .. } => Axes::Horizontal, + G::Scatter { .. } | G::Bubble => Axes::Values, + _ => Axes::Category, + } +} + +/// Group `g` drawn on axes of kind `family`: itself where it fits, else the nearest group that +/// does (a line-like series as lines, others as columns, bars or scatter). +fn fit_axes(g: G, family: Axes) -> G { + let own = axes_of(g); + if own == family || family == Axes::None { + return g; + } + let line_like = matches!(g, G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. }); + match family { + Axes::None => g, + Axes::Category if line_like => G::Line { stacked: false, markers: false }, + Axes::Category => G::Bar { bar: false, grouping: "clustered" }, + Axes::Horizontal => G::Bar { bar: true, grouping: "clustered" }, + Axes::Values => G::Scatter { lines: true }, + } +} + fn group_for(k: ChartKind) -> G { match k { ChartKind::ColumnStacked => G::Bar { bar: false, grouping: "stacked" }, @@ -561,7 +748,14 @@ fn multi_level_cat(f: &str, values: &str, wb: &Workbook, si: usize) -> Option String { +/// Series `s` in group `g`, drawn as kind `own`: a line or scatter series keeps its own markers +/// or lines within its group. +fn series_xml(s: &Series, idx: usize, g: G, own: ChartKind, wb: &Workbook, si: usize) -> String { + let g = match (g, group_for(own)) { + (G::Line { stacked, .. }, G::Line { markers, .. }) => G::Line { stacked, markers }, + (G::Scatter { .. }, mine @ G::Scatter { .. }) => mine, + _ => g, + }; let mut x = format!(""); if let Some(n) = &s.name { if is_ref(n) || is_defined_name(wb, si, n) { @@ -693,8 +887,10 @@ fn dlbls(show: bool) -> String { ) } -fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb: &Workbook, si: usize) -> String { - let sers: String = series.iter().map(|(i, s)| series_xml(s, *i, g, wb, si)).collect(); +/// Group `g` of `series`, each drawn as its kind in `kinds` (by series index). +fn group_xml(g: G, series: &[(usize, &Series)], kinds: &[ChartKind], ch: &Chart, axes: (u32, u32), wb: &Workbook, si: usize) -> String { + let sers: String = + series.iter().map(|(i, s)| series_xml(s, *i, g, kinds.get(*i).copied().unwrap_or(ChartKind::ColumnClustered), wb, si)).collect(); let dl = dlbls(ch.data_labels); let ax = format!("", axes.0, axes.1); match g { @@ -705,9 +901,11 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb if bar { "bar" } else { "col" } ) } - G::Line { stacked, .. } => format!( - "{sers}{dl}{ax}", - if stacked { "stacked" } else { "standard" } + // Each series states its own markers; an empty group's say whether the chart has them. + G::Line { stacked, markers } => format!( + "{sers}{dl}{ax}", + if stacked { "stacked" } else { "standard" }, + u8::from(markers || !series.is_empty()) ), G::Pie => format!("{sers}{dl}", ch.first_slice_angle % 360), G::Doughnut => format!( @@ -716,7 +914,11 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb ch.hole_size.clamp(10, 90) ), G::Area { grouping } => format!("{sers}{dl}{ax}"), - G::Scatter { .. } => format!("{sers}{dl}{ax}"), + // Each series states its own lines; an empty group's style says whether the chart has them. + G::Scatter { lines } => { + let style = if lines || !series.is_empty() { "lineMarker" } else { "marker" }; + format!("{sers}{dl}{ax}") + } G::Bubble => { format!("{sers}{dl}{ax}") } @@ -802,110 +1004,119 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str } s.push_str(""); let all: Vec<(usize, &Series)> = ch.series.iter().enumerate().collect(); - let primary_g; - let mut secondary: Option = None; - if ch.kind == ChartKind::Combo { - // Series without a kind of their own: the first is a column, the others lines (as drawn). - let kind = |i: usize, x: &Series| x.kind.filter(|k| *k != ChartKind::Combo).or((i > 0).then_some(ChartKind::Line)); - let is_line = |k: Option| matches!(k.map(group_for), Some(G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. })); - let bars: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && !is_line(kind(*i, x))).copied().collect(); - let lines: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && is_line(kind(*i, x))).copied().collect(); - let sec: Vec<(usize, &Series)> = all.iter().filter(|(_, x)| x.secondary).copied().collect(); - primary_g = G::Bar { bar: false, grouping: "clustered" }; - if !bars.is_empty() || (lines.is_empty() && sec.is_empty()) { - s.push_str(&group_xml(primary_g, &bars, ch, (1, 2), wb, si)); + // A stock chart is one group of its 3 or 4 series (high-low-close, open-high-low-close); + // other charts get one group per kind their series are drawn as, on each axis, in the order + // they first appear (a line's markers and a scatter's lines are the series' own). + let stock = ch.kind == ChartKind::Stock; + let kinds = ch.series_kinds(); + let group_of = |i: usize| match group_for(kinds.get(i).copied().unwrap_or(ChartKind::ColumnClustered)) { + G::Line { stacked, .. } => G::Line { stacked, markers: false }, + G::Scatter { .. } => G::Scatter { lines: true }, + g => g, + }; + // A chart without axes (a pie or doughnut chart) has no secondary axes either: its series + // are all one group. (A combination chart's pies are drawn as columns, on axes.) + let has_axes = (0..all.len()).any(|i| axes_of(group_of(i)) != Axes::None); + let groups = |secondary: bool| { + let mut out: Vec<(G, Vec<(usize, &Series)>)> = Vec::new(); + for &(i, x) in all.iter().filter(|(_, x)| stock || (x.secondary && has_axes) == secondary) { + let g = group_of(i); + match out.iter_mut().find(|(k, _)| *k == g) { + Some((_, members)) => members.push((i, x)), + None => out.push((g, vec![(i, x)])), + } } - if !lines.is_empty() { - s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &lines, ch, (1, 2), wb, si)); + // The groups on one pair of axes share its kind of axes; one that can't (a pie beside + // columns, a scatter beside lines) is drawn in the nearest group that can. + // A combination chart is drawn on category axes (its series' kinds say how). + let family = if ch.kind == ChartKind::Combo { + Axes::Category + } else { + out.iter().map(|(g, _)| axes_of(*g)).find(|a| *a != Axes::None).unwrap_or(Axes::None) + }; + // A stock group holds 3 or 4 series (high-low-close, open-high-low-close); others are + // lines, which join a line group already there rather than setting its grouping. + let (out, stock_lines): (Vec<_>, Vec<_>) = out.into_iter().partition(|(g, m)| *g != G::Stock || (3..=4).contains(&m.len())); + let stock_lines = stock_lines.into_iter().map(|(_, m)| (G::Line { stacked: false, markers: false }, m)); + // One group per type on a pair of axes (as Excel keeps them; `Chart::series_kind` gives + // the series of one type one grouping). Groups that fit the axes come first, so a group + // moved onto them joins one of its type there rather than setting its grouping. + let (fits, moved): (Vec<_>, Vec<_>) = out.into_iter().partition(|(g, _)| fit_axes(*g, family) == *g); + let mut fitted: Vec<(G, Vec<(usize, &Series)>)> = Vec::new(); + let moved = moved.into_iter().chain(stock_lines).map(|(g, m)| (fit_axes(g, family), m)); + for (g, members) in fits.into_iter().chain(moved) { + match fitted.iter_mut().find(|(k, _)| std::mem::discriminant(k) == std::mem::discriminant(&g)) { + Some((_, m)) => m.extend(members), + None => fitted.push((g, members)), + } } - if !sec.is_empty() { - let g = match sec.first().and_then(|(_, x)| x.kind).map(group_for) { - Some(b @ G::Bar { .. }) => b, - _ => G::Line { stacked: false, markers: false }, - }; - s.push_str(&group_xml(g, &sec, ch, (3, 4), wb, si)); - secondary = Some(g); + // Each group's series in their own order. + for (_, members) in &mut fitted { + members.sort_by_key(|(i, _)| *i); } - } else { - primary_g = match group_for(ch.kind) { - // A stock chart has 3 or 4 series (high-low-close, open-high-low-close). - G::Stock if !(3..=4).contains(&ch.series.len()) => G::Line { stacked: false, markers: false }, + fitted + }; + let (mut primary, mut sec) = if stock { (groups(false), Vec::new()) } else { (groups(false), groups(true)) }; + // With every series on the secondary axis, that axis is the only one. + if primary.is_empty() { + std::mem::swap(&mut primary, &mut sec); + } + // A chart without series still has a group of its kind, or it would not be read back (a + // stock group must hold series, so an empty stock chart has a line group). + if primary.is_empty() { + let g = match group_for(ch.kind) { + G::Stock => G::Line { stacked: false, markers: false }, g => g, }; - s.push_str(&group_xml(primary_g, &all, ch, (1, 2), wb, si)); + primary.push((g, Vec::new())); } - match primary_g { - G::Pie | G::Doughnut => {} - G::Scatter { .. } | G::Bubble => { - s.push_str(&axis_xml(&Ax { - cat: false, - id: 1, - cross: 2, - pos: "b", - delete: false, - grid: false, - title: ch.x_title.as_deref(), - crosses_max: false, - })); - s.push_str(&axis_xml(&Ax { - cat: false, - id: 2, - cross: 1, - pos: "l", - delete: false, - grid: ch.gridlines, - title: ch.y_title.as_deref(), - crosses_max: false, - })); - } - G::Bar { bar: true, .. } => { - s.push_str(&axis_xml(&Ax { - cat: true, - id: 1, - cross: 2, - pos: "l", - delete: false, - grid: false, - title: ch.x_title.as_deref(), - crosses_max: false, - })); - s.push_str(&axis_xml(&Ax { - cat: false, - id: 2, - cross: 1, - pos: "b", - delete: false, - grid: ch.gridlines, - title: ch.y_title.as_deref(), - crosses_max: false, - })); - } - _ => { - s.push_str(&axis_xml(&Ax { - cat: true, - id: 1, - cross: 2, - pos: "b", - delete: false, - grid: false, - title: ch.x_title.as_deref(), - crosses_max: false, - })); - s.push_str(&axis_xml(&Ax { - cat: false, - id: 2, - cross: 1, - pos: "l", - delete: false, - grid: ch.gridlines, - title: ch.y_title.as_deref(), - crosses_max: false, - })); - } + for (g, members) in &primary { + s.push_str(&group_xml(*g, members, &kinds, ch, (1, 2), wb, si)); } - if secondary.is_some() { - s.push_str(&axis_xml(&Ax { cat: true, id: 3, cross: 4, pos: "b", delete: true, grid: false, title: None, crosses_max: false })); - s.push_str(&axis_xml(&Ax { cat: false, id: 4, cross: 3, pos: "r", delete: false, grid: false, title: None, crosses_max: true })); + for (g, members) in &sec { + s.push_str(&group_xml(*g, members, &kinds, ch, (3, 4), wb, si)); + } + let family = |gs: &[(G, Vec<(usize, &Series)>)]| gs.iter().map(|(g, _)| axes_of(*g)).find(|a| *a != Axes::None).unwrap_or(Axes::None); + let primary_axes = family(&primary); + // The primary axes, placed by their kind. + let (cat, cat_pos, val_pos) = match primary_axes { + Axes::None => (true, "", ""), + Axes::Values => (false, "b", "l"), + Axes::Horizontal => (true, "l", "b"), + Axes::Category => (true, "b", "l"), + }; + if primary_axes != Axes::None { + s.push_str(&axis_xml(&Ax { + cat, + id: 1, + cross: 2, + pos: cat_pos, + delete: false, + grid: false, + title: ch.x_title.as_deref(), + crosses_max: false, + })); + s.push_str(&axis_xml(&Ax { + cat: false, + id: 2, + cross: 1, + pos: val_pos, + delete: false, + grid: ch.gridlines, + title: ch.y_title.as_deref(), + crosses_max: false, + })); + } + // The secondary axes: their categories (or x values) hidden, their values on the far side. + let (cat, cat_pos, val_pos) = match family(&sec) { + Axes::None => (true, "", ""), + Axes::Values => (false, "b", "r"), + Axes::Horizontal => (true, "l", "t"), + Axes::Category => (true, "b", "r"), + }; + if !cat_pos.is_empty() { + s.push_str(&axis_xml(&Ax { cat, id: 3, cross: 4, pos: cat_pos, delete: true, grid: false, title: None, crosses_max: false })); + s.push_str(&axis_xml(&Ax { cat: false, id: 4, cross: 3, pos: val_pos, delete: false, grid: false, title: None, crosses_max: true })); } if let Some(t) = &ch.data_table { let _ = write!( diff --git a/crates/xlsx/src/tests/chart_combo_kinds.rs b/crates/xlsx/src/tests/chart_combo_kinds.rs index 6857683ada..04890de537 100644 --- a/crates/xlsx/src/tests/chart_combo_kinds.rs +++ b/crates/xlsx/src/tests/chart_combo_kinds.rs @@ -44,3 +44,423 @@ fn line_first_group_stays_a_line() { assert!(matches!(k[0], Some(ChartKind::Line | ChartKind::LineMarkers))); assert_eq!(k[1], Some(ChartKind::ColumnClustered)); } + +/// Outside a combo, a series keeps its own markers or lines where they differ from its chart's, +/// read and written. The chart's kind is its first series'. +#[test] +fn series_keep_their_own_markers_and_lines() { + use gridcraft_model::{Chart, Series, Workbook}; + let no_marker = "Data!$A$1:$A$5"; + let xml = format!( + "{}", + line(&(no_marker.to_string() + &ser(1))) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!((ch.kind, ch.series.iter().map(|s| s.kind).collect::>()), (ChartKind::Line, vec![None, Some(ChartKind::LineMarkers)])); + let series = |kind| Series { values: "Sheet1!$A$1:$A$3".into(), kind, ..Series::default() }; + for (kind, kinds) in + [(ChartKind::Line, vec![None, Some(ChartKind::LineMarkers)]), (ChartKind::ScatterLines, vec![Some(ChartKind::Scatter), None])] + { + let chart = Chart { kind, series: kinds.iter().map(|k| series(*k)).collect(), ..ch.clone() }; + let written = crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1"); + let back = read_chart(&parse(written.as_bytes()).unwrap()).unwrap(); + // XLSX has no chart-wide kind besides its series': each series is drawn as it was. + let drawn = |c: &Chart| (0..c.series.len()).map(|i| c.series_kind(i)).collect::>(); + assert_eq!(drawn(&back), drawn(&chart), "{kind:?}"); + } +} + +/// A combo chart is written with one group per kind its series are drawn as, and read back in +/// the series' own order. +#[test] +fn combo_series_keep_their_kinds_and_order() { + use gridcraft_model::{Chart, Series, Workbook}; + let xml = format!( + "{}{}", + bar(&ser(0)), + line(&ser(1)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + for kinds in [ + vec![ChartKind::ColumnClustered, ChartKind::Area], + vec![ChartKind::ColumnStacked, ChartKind::LineMarkers], + vec![ChartKind::LineMarkers, ChartKind::ColumnClustered], + ] { + let series: Vec = kinds + .iter() + .enumerate() + .map(|(i, k)| Series { values: format!("Sheet1!${}$1:${}$3", ["B", "C"][i], ["B", "C"][i]), kind: Some(*k), ..Series::default() }) + .collect(); + let chart = Chart { kind: ChartKind::Combo, series, ..base.clone() }; + let back = read_chart(&parse(crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1").as_bytes()).unwrap()).unwrap(); + let drawn = |c: &Chart| (0..c.series.len()).map(|i| (c.series_kind(i), c.series[i].values.clone())).collect::>(); + assert_eq!(drawn(&back), drawn(&chart), "{kinds:?}"); + } + // Groups that can't share one pair of axes are drawn in the first one's kind: a pie beside + // columns as columns, its axes all present. (A combination's bars are drawn as columns.) + { + let (kinds, want) = (vec![ChartKind::Pie, ChartKind::ColumnClustered], ChartKind::ColumnClustered); + let series: Vec = kinds.iter().map(|k| Series { values: "Sheet1!$B$1:$B$3".into(), kind: Some(*k), ..Series::default() }).collect(); + let chart = Chart { kind: ChartKind::Combo, series, ..base.clone() }; + let xml = crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1"); + let back = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert!((0..2).all(|i| back.series_kind(i) == want), "{kinds:?}: {xml}"); + assert!(back.series.iter().all(|s| !s.secondary), "{kinds:?}"); + assert!(xml.contains(""), "{kinds:?}: {xml}"); + } +} + +/// A chart of one kind with a series on the secondary axis keeps it, and reads back as that +/// kind, not a combination. +#[test] +fn one_kind_on_two_axes_stays_one_kind() { + use gridcraft_model::{Chart, Series, Workbook}; + let xml = format!( + "{}", + bar(&ser(0)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let series = vec![ + Series { values: "Sheet1!$B$1:$B$3".into(), ..Series::default() }, + Series { values: "Sheet1!$C$1:$C$3".into(), secondary: true, ..Series::default() }, + ]; + let chart = Chart { kind: ChartKind::ColumnClustered, series, ..base }; + let back = read_chart(&parse(crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1").as_bytes()).unwrap()).unwrap(); + assert_eq!(back.kind, ChartKind::ColumnClustered); + assert_eq!(back.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), vec![(None, false), (None, true)]); +} + +/// A stock chart with volume: the stock group of 4 series stays a stock group beside the +/// volume columns. +#[test] +fn stock_with_volume_keeps_its_stock_group() { + use gridcraft_model::{Chart, Series, Workbook}; + let xml = format!( + "{}", + bar(&ser(0)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let mut series = vec![Series { values: "Sheet1!$B$1:$B$3".into(), kind: Some(ChartKind::ColumnClustered), ..Series::default() }]; + series.extend((0..4).map(|_| Series { values: "Sheet1!$C$1:$C$3".into(), kind: Some(ChartKind::Stock), secondary: true, ..Series::default() })); + let chart = Chart { kind: ChartKind::Combo, series, ..base }; + let written = crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1"); + assert!(written.contains(""), "{written}"); + let back = read_chart(&parse(written.as_bytes()).unwrap()).unwrap(); + assert_eq!((1..5).map(|i| back.series_kind(i)).collect::>(), vec![ChartKind::Stock; 4]); +} + +/// A stock series too few for a stock group is saved as a line in the line group already on its +/// axes: the stacked lines after it stay stacked. +#[test] +fn a_lone_stock_series_does_not_unstack_the_lines_beside_it() { + use ChartKind::*; + let chart = chart_of(Combo, &[(Some(Stock), false), (Some(LineStacked), false), (Some(LineStacked), false)]); + let (xml, back) = round_trip(&chart); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + assert!(xml.contains(""), "{xml}"); + assert_eq!((back.series_kind(1), back.series_kind(2)), (LineStacked, LineStacked), "{xml}"); +} + +/// The primary axes are the pair whose value axis is on the left, whichever group the file +/// lists first. +#[test] +fn a_secondary_scatter_listed_first_stays_secondary() { + let sc = |s: &str, a: u32, b: u32| { + format!("{s}") + }; + let ax = + |id: u32, cross: u32, pos: &str| format!(""); + let xml = format!( + "{}{}{}{}{}{}", + sc(&ser(0), 30, 40), + sc(&ser(1), 10, 20), + ax(10, 20, "b"), + ax(20, 10, "l"), + ax(30, 40, "b"), + ax(40, 30, "r") + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.series.iter().map(|s| s.secondary).collect::>(), vec![true, false]); +} + +/// A chart of `kind` whose series have `kinds` (and secondary flags). +fn chart_of(kind: ChartKind, kinds: &[(Option, bool)]) -> gridcraft_model::Chart { + use gridcraft_model::{Chart, Series}; + let xml = format!( + "{}", + bar(&ser(0)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let series = kinds + .iter() + .enumerate() + .map(|(i, (k, secondary))| Series { values: format!("Sheet1!$B${0}:$B${0}", i + 1), kind: *k, secondary: *secondary, ..Series::default() }) + .collect(); + Chart { kind, series, ..base } +} + +/// The chart written to XLSX, and read back. +fn round_trip(chart: &gridcraft_model::Chart) -> (String, gridcraft_model::Chart) { + let xml = crate::chart::write_chart(&gridcraft_model::Workbook::new(), 0, chart, "Book1"); + let back = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + (xml, back) +} + +/// What a chart draws: each series' values, kind and axis. +fn drawn(c: &gridcraft_model::Chart) -> Vec<(String, ChartKind, bool)> { + let any_primary = c.series.iter().any(|s| !s.secondary); + (0..c.series.len()).map(|i| c.series_kind(i)).zip(&c.series).map(|(k, s)| (s.values.clone(), k, s.secondary && any_primary)).collect() +} + +/// A chart written to XLSX and read back draws the same series, kinds and axes. +fn assert_round_trips(kind: ChartKind, kinds: &[(Option, bool)]) -> String { + let chart = chart_of(kind, kinds); + let (xml, back) = round_trip(&chart); + assert_eq!(drawn(&back), drawn(&chart), "{kinds:?}: {xml}"); + xml +} + +/// Pies and doughnuts have no axes: a series marked secondary (left from a combo before the +/// type changed) stays in the one group, so Excel draws one pie, not two on top of each other. +#[test] +fn pies_and_doughnuts_are_one_group_whatever_the_secondary_flags() { + for (kind, tag) in [(ChartKind::Pie, ""), (ChartKind::Doughnut, "")] { + let (xml, back) = round_trip(&chart_of(kind, &[(None, false), (None, true)])); + assert_eq!(xml.matches(tag).count(), 1, "{xml}"); + assert!(!xml.contains(""), "{xml}"); + assert_eq!((back.kind, back.series.len()), (kind, 2)); + } +} + +/// A combination chart's pies and doughnuts are drawn as columns, on axes: on the secondary +/// axis beside other secondary series, with primary axes always written, and a combo of only +/// pies and doughnuts is one group of columns. +#[test] +fn combo_pies_are_columns_on_their_own_axes() { + use ChartKind::*; + let xml = assert_round_trips(Combo, &[(Some(Pie), true), (Some(ColumnClustered), true)]); + assert!(xml.contains("") && !xml.contains(""), "{xml}"); + let xml = assert_round_trips(Combo, &[(Some(ColumnClustered), false), (Some(Line), true), (Some(Pie), true)]); + assert_eq!(xml.matches("").count(), 2, "{xml}"); + let xml = assert_round_trips(Combo, &[(Some(Pie), false), (Some(Doughnut), false)]); + assert!(!xml.contains("") && !xml.contains(""), "{xml}"); + assert_eq!(xml.matches("").count(), 1, "{xml}"); +} + +/// Excel keeps one group per type on a pair of axes: clustered and stacked columns (lines and +/// stacked lines, areas and stacked areas) on the same axes are written as one group, drawn +/// alike before saving and after reopening. +#[test] +fn one_group_per_type_on_a_pair_of_axes() { + use ChartKind::*; + for (kinds, tag) in [ + (vec![(Some(ColumnStacked), false), (Some(Pie), false), (Some(Line), false)], ""), + (vec![(Some(Pie), false), (Some(ColumnStacked), false), (Some(Line), false)], ""), + (vec![(Some(ColumnClustered), false), (Some(ColumnStacked), false)], ""), + (vec![(Some(ColumnStacked), false), (Some(ColumnClustered), false), (Some(Line), false)], ""), + (vec![(Some(Line), false), (Some(LineStacked), false), (Some(ColumnClustered), false)], ""), + (vec![(Some(LineStacked), false), (Some(LineMarkers), false), (Some(ColumnClustered), false)], ""), + (vec![(Some(Area), false), (Some(AreaStacked), false), (Some(ColumnClustered), false)], ""), + ] { + let xml = assert_round_trips(Combo, &kinds); + assert_eq!(xml.matches(tag).count(), 1, "{kinds:?}: {xml}"); + } + // A stacked column after a clustered one is drawn clustered, as it is saved. + let chart = chart_of(Combo, &[(Some(ColumnClustered), false), (Some(ColumnStacked), false)]); + assert_eq!((chart.series_kind(0), chart.series_kind(1)), (ColumnClustered, ColumnClustered)); + // On separate axes each keeps its own grouping. + let xml = assert_round_trips(Combo, &[(Some(ColumnClustered), false), (Some(ColumnStacked), true), (Some(Line), false)]); + assert_eq!(xml.matches("").count(), 2, "{xml}"); +} + +/// A merged group writes its series in their own order: a bubble series drawn as a column joins +/// the columns where it stands. +#[test] +fn a_merged_group_keeps_its_series_in_order() { + use ChartKind::*; + let (xml, back) = round_trip(&chart_of(Combo, &[(Some(ColumnClustered), false), (Some(Bubble), false), (Some(ColumnClustered), false)])); + assert_eq!(back.series.iter().map(|s| s.values.as_str()).collect::>(), vec!["Sheet1!$B$1:$B$1", "Sheet1!$B$2:$B$2", "Sheet1!$B$3:$B$3"]); + let orders: Vec<&str> = xml.match_indices("") && !xml.contains(""), "{kinds:?}: {xml}"); + assert!(xml.contains(""), "{kinds:?}: {xml}"); + } +} + +/// A combination chart's chartex series (histogram, waterfall, funnel, treemap, sunburst, box & +/// whisker) are drawn and saved as clustered columns, sharing the first column's grouping. +#[test] +fn combo_chartex_series_are_columns() { + use ChartKind::*; + for k in [Histogram, Waterfall, Funnel, Treemap, Sunburst, BoxWhisker] { + let xml = assert_round_trips(Combo, &[(Some(ColumnStacked), false), (Some(k), false), (None, false)]); + assert_eq!(xml.matches("").count(), 1, "{k:?}: {xml}"); + assert_round_trips(Combo, &[(Some(k), false), (Some(ColumnStacked), false), (Some(Line), false)]); + let chart = chart_of(Combo, &[(Some(Bubble), false), (Some(k), false)]); + assert_eq!(round_trip(&chart).1.supports_data_table(), chart.supports_data_table(), "{k:?}"); + } +} + +/// A chart without series keeps a group of its kind, so it is read back as that kind rather +/// than dropped (an empty combo as clustered columns, an empty stock chart as a line chart: a +/// stock group must hold series). +#[test] +fn a_chart_without_series_survives_a_round_trip() { + use ChartKind::*; + let kinds = [ + ColumnClustered, + ColumnStacked100, + BarStacked, + Line, + LineMarkers, + LineStacked, + Pie, + Doughnut, + Area, + AreaStacked, + Scatter, + ScatterLines, + Bubble, + Radar, + Stock, + Combo, + ]; + for kind in kinds { + let (xml, back) = round_trip(&chart_of(kind, &[])); + let want = match kind { + Combo => ColumnClustered, + Stock => Line, + k => k, + }; + assert_eq!((back.kind, back.series.len()), (want, 0), "{kind:?}: {xml}"); + } +} + +/// The primary axes are found in one pass over the value axes, however many groups a file has: +/// eight times the groups is about eight times the work, not sixty-four. +#[test] +fn many_groups_are_read_in_linear_time() { + // Every group has a series and its own value axis on the right, so no group is the primary + // pair and every group's value axis is looked up among all the others. + let visits = |n: usize| { + let groups: String = (0..n) + .map(|i| { + format!( + "{}", + ser(i), + 2 * i + 1, + 2 * i + 2 + ) + }) + .collect(); + let axes: String = (0..n).map(|i| format!("", 2 * i + 2)).collect(); + let xml = format!( + "{groups}{axes}" + ); + let doc = parse(xml.as_bytes()).unwrap(); + crate::chart::VAL_AXIS_VISITS.with(|v| v.set(0)); + let ch = read_chart(&doc).unwrap(); + assert_eq!(ch.series.len(), n); + crate::chart::VAL_AXIS_VISITS.with(|v| v.get()) + }; + let (small, large) = (visits(300), visits(2_400)); + assert!(small >= 300, "every value axis is looked at: {small}"); + assert!(large < 16 * small, "eight times the groups took {large} visits against {small}"); +} + +/// An empty group of another kind before the groups with series (as another writer may leave) +/// sets neither the chart's axes nor which series are secondary. +#[test] +fn an_empty_group_sets_neither_axes_nor_secondary() { + let ax = |tag: &str, id: u32, cross: u32, pos: &str, title: &str| { + format!( + "{title}" + ) + }; + let xml = format!( + "\ + {AX}\ + {}\ + {}{}{}{}", + ser(0), + ax("catAx", 1, 2, "b", "BARCAT"), + ax("valAx", 2, 1, "l", "BARVAL"), + ax("valAx", 3, 4, "b", "SCX"), + ax("valAx", 4, 3, "l", "SCY"), + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.kind, ChartKind::ScatterLines); + assert!(!ch.series[0].secondary); + assert_eq!((ch.x_title.as_deref(), ch.y_title.as_deref()), (Some("SCX"), Some("SCY"))); +} + +/// An axis element (`tag` with id, crossing axis, side, title, and whether it is deleted). +fn axis(tag: &str, id: u32, cross: u32, pos: &str, title: Option<&str>, deleted: bool) -> String { + let title = title.map_or(String::new(), |t| format!("{t}")); + format!( + "{title}", + u8::from(deleted) + ) +} + +fn titles_of(plot: &str) -> (Option, Option) { + let xml = format!( + "{plot}" + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + (ch.x_title, ch.y_title) +} + +/// Axis titles come from shown axes before deleted ones, and the primary pair's group says +/// whether they are a scatter's two value axes. +#[test] +fn titles_come_from_shown_axes_of_the_primary_pair() { + let some = |x: &str, y: &str| (Some(x.to_string()), Some(y.to_string())); + // Series only on axes 3/4 (whose category axis is deleted), beside an empty group on 1/2. + let plot = format!( + "{AX}\ + {}{}{}{}{}", + ser(0), + axis("catAx", 1, 2, "b", Some("PCAT"), false), + axis("valAx", 2, 1, "l", Some("PVAL"), false), + axis("catAx", 3, 4, "b", None, true), + axis("valAx", 4, 3, "r", Some("SVAL"), false), + ); + assert_eq!(titles_of(&plot), some("PCAT", "SVAL")); + // A secondary line group before the primary scatter group. + let plot = format!( + "{}\ + {}{AX}{}{}{}{}", + ser(0), + ser(1), + axis("catAx", 3, 4, "b", Some("SCAT"), true), + axis("valAx", 4, 3, "r", Some("SVAL"), false), + axis("valAx", 1, 2, "b", Some("X"), false), + axis("valAx", 2, 1, "l", Some("Y"), false), + ); + assert_eq!(titles_of(&plot), some("X", "Y")); +} diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 46a953bc1d..b40be2b158 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -909,18 +909,17 @@ fn two_column_groups_on_different_axes_preserve_secondary_and_kind() { ); let (wb, _) = read_xlsx(&bytes).unwrap(); let ch = &wb.sheet(0).unwrap().charts[0]; - assert_eq!(ch.kind, gridcraft_model::ChartKind::Combo); + // Series of one kind are one chart, a column chart with a secondary-axis series. + assert_eq!(ch.kind, gridcraft_model::ChartKind::ColumnClustered); assert!(!ch.series[0].secondary); assert!(ch.series[1].secondary); - assert_eq!(ch.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); - assert_eq!(ch.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + assert_eq!(ch.series_kinds(), vec![gridcraft_model::ChartKind::ColumnClustered; 2]); let out = crate::write_xlsx(&wb).unwrap(); let (wb2, _) = read_xlsx(&out).unwrap(); let ch2 = &wb2.sheet(0).unwrap().charts[0]; - assert_eq!(ch2.kind, gridcraft_model::ChartKind::Combo); + assert_eq!(ch2.kind, gridcraft_model::ChartKind::ColumnClustered); assert!(!ch2.series[0].secondary); assert!(ch2.series[1].secondary); - assert_eq!(ch2.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); - assert_eq!(ch2.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + assert_eq!(ch2.series_kinds(), vec![gridcraft_model::ChartKind::ColumnClustered; 2]); } diff --git a/docs/chart-parity.md b/docs/chart-parity.md index 4967b00207..37f482eeb0 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -1,6 +1,6 @@ # Chart parity -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: combo series drawn and saved by their own kind; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's chart types and chart elements against GridCraft. Part of [target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated). @@ -32,7 +32,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Box & Whisker | 1 | 1 of 1 | | | Waterfall, Funnel | 2 | 2 of 2 | | | Filled map | 1 | 0 | needs geographic boundary data (licensing decision) | -| Combo | custom combinations, secondary axis | yes (line on secondary axis) | | +| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | | | **Total** | ~60 subtypes | **26 (~43%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | ## Chart elements and formatting @@ -49,7 +49,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Axis options | min/max/units, log scale, reverse order, crossing point, display units, date axis, number format | **missing** (auto only) | | Multi-level category axis (a category range two or more columns wide beside the values: year beside month) | the outer levels grouped under the labels with separators | read (`multiLvlStrRef`), drawn (rows under the labels; columns beside them in bar charts; up to three outer levels), written back with Excel's level caches | | Doughnut hole size, first slice angle | 10–90% hole (Excel default 75%), 0–359° first slice | Format Chart pane sliders; read from and written to `c:holeSize` / `c:firstSliceAng`; documents saved before the setting existed keep their old 50% hole | -| Secondary axis | any series | line series in combo charts | +| Secondary axis | any series | any combo series; a one-kind chart's secondary series keep their axis in XLSX | | Trendlines | linear, exponential, logarithmic, polynomial, power, moving average, equation and R² | all six types, several per series, name, forward/backward forecast, set intercept, equation and R² label, line colour/width/dash; read, written and drawn on 2-D column, bar, line, area, scatter and bubble series; `chart.addElement` `trendline` adds/removes them. No Format Trendline pane, label position/number format not kept | | Error bars | fixed, %, standard deviation/error, custom | **missing** | | Up/down bars, high-low lines, drop lines, series lines | yes | **missing** | @@ -95,6 +95,37 @@ qualifier: with a bare name in `` it draws the whole chart blank, without a (observed in Excel for Windows, Microsoft 365). External books (`[1]Sheet1!…`) are kept as they are (#1686). Such series get no `numCache`/`strCache` on save (#1690). +Each series is drawn and saved as the kind `Chart::series_kind` gives it: in a combo chart its +own kind (by default the first a column and the rest lines), elsewhere the chart's kind, with a +line's own markers or a scatter's own lines kept. A combo chart is drawn on category axes: its +bars as columns, its pies, doughnuts, bubbles and chartex kinds (histogram, waterfall, funnel, +treemap, sunburst, box & whisker) as clustered columns, its scatter and radar series as lines (a +markers-only scatter with markers). In +a combo chart the series of one type on one pair of axes share the first one's grouping, as Excel +keeps them: a stacked column after a clustered one is drawn clustered, and a stacked line after +an unstacked one unstacked. Changing the chart type (to any type but a combo) applies it to every +series, dropping their own kinds; setting the type a chart already has keeps them. + +The XLSX writer writes one chart group per type on each pair of axes, with axes of the kind those +groups need (category axes for a combo; category, horizontal-bar or value axes otherwise), a secondary pair whenever a series is on it, and a stock group only for 3 +or 4 series. A pie or doughnut chart has no axes, so its series are one group whatever their +secondary flags. A chart without series is written with one empty group of its kind, so it +reopens as that kind (an empty combo as clustered columns, an empty stock chart as a line chart) +rather than vanishing; chartex charts (histogram, waterfall and the rest) without series are +still not kept. The reader takes the primary axes from the value axis on the left or bottom, and +orders series by `c:order`, then sets the chart's kind and each series' own kind with +`Chart::set_drawn_kinds`, the rule any reader of per-series kinds shares. A combo whose series all draw as one type reopens as a chart of +that type (it draws the same). + +Known gaps: a one-kind bar chart's secondary series get secondary axes in XLSX, which the +renderer does not yet draw for horizontal charts; a stock series in a combo +beside stacked lines is saved in the stacked line group but drawn unstacked; a stock series +beside columns (other than a 3- or 4-series stock group) is saved as a line and reopens as one; +a per-series line or scatter kind left in an older GridCraft JSON workbook by a type change is +honoured (markers gained or lines lost) rather than migrated, since it can't be told from a +file's own per-series kind; the Forecast Sheet's +column chart draws and saves its forecast series as columns, not lines. + ## Work (40–60 h) 1. Preserve unmodelled chart XML on round-trip (keep the original part, patch only edited fields): 6–10 h. @@ -109,6 +140,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690). | Date | Change | Summary | |---|---|---| | 2026-11-16 | minor | A selected chart outlines its series names (red), category labels (purple) and values (one blue block), and the values outline has corner handles: dragging one changes the block the series plot through the new `chart.setValuesRange` command, keeping each series' formatting (#4389, #4390). Engine and real-input UI tests cover growing, shrinking, adding series, undo and Esc. No readiness score change. | +| 2026-11-14 | minor | Combo series drawn and saved by their own kind (`Chart::series_kind`): areas, stacked columns and marker lines in combos round-trip XLSX; the series of one type on one pair of axes share the first one's grouping on screen and in the file (as Excel keeps them); combo charts are drawn and saved on category axes (pies, doughnuts, bubbles and chartex kinds as columns, scatter and radar as lines); one-kind charts keep secondary-axis series (pie and doughnut charts stay one group); changing the type applies it to every series; charts without series survive XLSX. No readiness score change. | | 2026-11-07 | minor | Chart-data-table keys use the shared plot-kind helper with their series index after #1150. A focused regression checks the first combo series uses a column key and later series use line keys. No readiness score change. | | 2026-11-02 | minor | Charts move and resize from eight handles, each moving only its own edges (#190); resizing leaves the work list (1–2 h, within the 40–60 h rounding) | | 2026-11-01 | minor | Chart data tables for column, bar, line, area and compatible combo charts: command/UI controls, formatted source values, blanks, grouped category headers, legend keys, independent borders, shared print/PDF rendering and native c:dTable import/export. Dense tables show a space notice; no readiness score change. | From 8a7fe1bec274c1db25e515dda016e8b5afd3721c Mon Sep 17 00:00:00 2001 From: Aleksander Helgaker Date: Mon, 23 Nov 2026 23:58:18 +0100 Subject: [PATCH 07/10] engine, model: one workbook-wide reference rewrite; rule formulas follow their ranges (ODS groundwork) (#4136) * engine, model: one workbook-wide reference rewrite; rule formulas follow their ranges Workbook::rewrite_references(&dyn Fn(RefHost, Expr) -> Expr) is the single walker over every place a workbook holds a reference: cell formulas (keeping array range and spill kind), defined names, conditional formats, validation, in-workbook links, chart series and sources, sparklines and PivotTable sources. Sheet rename and delete, defined-name and table rename, row/column and cell insert/delete and cut-paste all go through it instead of their own lists of holders, so a rename now also reaches pivot sources, rules and validations; inserting rows above a rule moves its formulas; deleting a sheet makes rule/validation references #REF! and no longer turns legacy arrays into spills; table rename keeps legacy arrays. A copied sheet's charts plot the copy. Conditional-format and validation formulas are re-hosted by how their ranges moved (rehost_rule, CfRule::relative_formulas_mut/formulas_mut, Validation::formulas_mut): deleting a rule's first row no longer makes it #REF!, ranges moved whole or left in place keep their formulas, thresholds are read as written. A cut takes rules with its cells (Rule trait, remove_rule_cells, moved_rule_parts) and moves their references once. A sheet-qualified name splits at its last '!' when a sheet is renamed. * engine, model: review fixes for the workbook-wide reference rewrite - rehost_rule takes the rule's top-left from all its ranges before the edit, so removing the range that held it (deleting its rows or cells) re-hosts the formulas instead of leaving #REF!. - Internal hyperlink targets are no longer rewritten: they keep the place they name as typed, as main and Excel do. - A cut can't be transposed or tiled by Paste Special (as in Excel); its rules and references followed the block unturned. - rewrite_references copies a sheet only when something on it changes, so untouched sheets stay shared with undo snapshots. - docs/architecture.md: revision row moved under Revision history; section updated. * engine, model: re-review touch-ups for the reference rewrite - The multi-area rehost test checks deleting the first area's cells both shifting up and shifting left (the comment said up, the test did left). - rewrite_references checks rules, validations, charts, sparklines and pivots on the borrowed sheet and copies a list only when something in it changes (CfRule::formulas, Validation::formulas, read-only). A chart source already holding #REF! is dropped by any rewrite again. * engine, model: round-2 review fixes for the reference rewrite - A cut to another sheet names the source sheet in all of a conditional format's formulas, thresholds included: a colour scale's, data bar's or icon set's threshold formula kept reading the destination sheet's cells. - A chart series name that is a bare word and not a defined name is a label, as the chart reads it: renaming a table of that name no longer rewrites it. Renaming a defined name rewrites formulas before the old name is dropped, so a series named by it still follows. - The walker's doc no longer lists deleting names among the edits that go through it; a test comment says what it checks. * engine, model: round-3 review fixes for the reference rewrite - A chart series name is left as written unless the chart reads it as a reference: it starts with `=`, names a sheet, or is a defined name its own sheet sees. A name scoped to another sheet, or a label shaped like a cell (`Q1`), is no longer rewritten (corrects round 2's check, which looked at names in every scope and only exempted bare words). - A chart source block is dropped as gone only when its formula holds `#REF!`, not its text: a sheet may be named `#REF!`. - Defined names are handed to the rewrite on `NAME_HOST` (`[]`), which no sheet name can be, instead of a NUL that a sheet could be renamed to. - The walker's doc and docs/architecture.md list a PivotChart's link and a slicer's table among what it does not visit. * engine: Move Columns takes its columns' rules along as a cut does A conditional format or validation wider than the moved columns was left in place by the move step while its formulas were moved as references into the block, so the cells left behind checked the wrong column and the moved column lost the rule. Move Columns now moves the rules' parts in the moved columns as Cut and Paste does (`move_cut_rules`), and the rest of the rule re-hosts from its new top-left cell. * engine: round-5 review fixes for the reference rewrite - Move Columns moves its rules before the columns' features shift (corrects round 4): moved left, a rule whose whole range was in the moved columns was shifted, re-hosted and then re-hosted again from mixed positions, so the parts left behind checked the wrong column. - Copying a sheet keeps a chart's series and source text as written unless it names the copied sheet: a series name `=A1` lost its `=` and was read as the label "A1". - Docs and comments say what the code does: `move_cut_rules` serves Move Columns too, `rewrite_all_formulas` and `rename_name_in_formulas` point at the walker, and docs/architecture.md names Move Columns; `sheet_rename_renames_a_pivot_source` is named for what it checks. * docs: architecture: a rule's one formula across a partial shift of its cells A conditional format or validation keeps one formula for all its cells, so an insert or delete inside its range, or Move Columns across it, leaves relative references at the cells on the far side of the shift reading where the top-left cell's reference puts them. * engine: review fixes for the reference rewrite (CodeRabbit) A cut moves the rules its cells hold when it is pasted, not the clipboard snapshot's: a rule cleared after the cut came back at the destination. A table rename leaves a bare name in a workbook name alone when a workbook-level defined name of that name exists, as it does in cells. * engine: a cut is not pasted skipping blanks A cut's rules replace the destination's under the whole block, so a Skip Blanks paste of it dropped validation under the cells it left alone. Paste Special now refuses Skip Blanks for a cut, as it already refuses Transpose and tiling (Excel offers none of them for a cut). * table.rename: a PivotTable table source follows even when a defined name shadows it A bare pivot source binds to the table before a defined name, so the shadowing that keeps formula names on the defined name does not apply. Co-Authored-By: Claude Opus 5.5 * model: rewrite_references keeps a chart source that was already broken Only a source the edit breaks is dropped. A source already #REF! (from a file or an earlier edit) stays as it was through an unrelated edit, such as renaming a defined name it does not use. * paste: a cut moves on its sheet as it is named now A cut whose source sheet is renamed before the paste rebased its moved rules, and the references to its cells, against the name the clipboard saw, which no longer exists. A cut in the same workbook now uses the live sheet name. * formulas: renaming a defined name leaves LET and LAMBDA locals alone The rename walk now tracks the locals in scope: a LET or LAMBDA local of the old name is not the defined name and keeps its name, and a rename that a local of the new name would capture is refused and changes nothing. It is the one walk for cells, names, rules and Python cells. * formulas: a name rename renames calls to it and is refused where a sheet name would take it A call to a defined LAMBDA by name (`FnOld(4)`) now follows a rename of the name; a called LET or LAMBDA local of the old name stays as it is. A workbook name renamed to a name a sheet defines for itself would be read as that sheet's name there, so that rename is refused. * paste: a cut is refused as Paste Link or into filtered-out rows before its source is cleared Paste Link would write links to the cells the cut empties, and a destination in rows the filter hides would skip every cell the cut writes; both lost the cut cells. * sheets: a pending cut ends when a sheet edit puts another sheet in its place A cut names its sheet by its place among the tabs, so after inserting, deleting or moving a sheet before it, a paste took cells and rules from whichever sheet had that place. The cut now ends when its place holds another sheet (or none); a cut whose sheet kept its place stays, and a copy reads its own snapshot and stays. * model: a sheet-level name's references are rewritten on its own sheet Unqualified references in a sheet-level name are read on its scope sheet, so rewrite_references now hosts them there: inserting a row above one moves it, as it moves a cell formula on that sheet. Workbook-level names keep NAME_HOST. * model: a PivotTable source that names a table is left out of a name's rewrite A bare source that is a table's name reads the table before a defined name of that name, so renaming the defined name no longer moves the PivotTable off its table. * sheet: a rule follows its top-left cell through a partial cell delete or insert Deleting cells in only the first column of a rule's range keeps the range's size, so it was treated as moved whole and its formulas stayed written for the deleted cell (=A1>0 became =#REF!>0). When the cell the shift puts at the top-left was one of the rule's own cells, the formulas now follow it. * sheet.moveColumns: a moved column's part of a rule reads what the column read The moved part was taken after the columns were made room for, when the rule's formula (written for its top-left) no longer said what the moved cells read: a rule on B1:D1 testing =A1>0, with D moved before B, left the moved cell testing old B instead of old C. The parts are now taken from the sheet before the insert and follow it as the cells' formulas do. move_cut_rules' placing half is place_moved_rules, shared. * tests: the broken-chart-source test rewrites the chart it checks A series now reads the renamed name, so the rename takes the branch that rewrites the chart, and the test checks the series changed while the broken source stayed. * Revert "sheets: a pending cut ends when a sheet edit puts another sheet in its place" This reverts commit 1569394173dc140f9eef29e13757b8ca9a567cc8. * Revert "paste: a cut is refused as Paste Link or into filtered-out rows before its source is cleared" This reverts commit 80e7525d290254876756f4c83d594fa846107a24. * Revert "formulas: a name rename renames calls to it and is refused where a sheet name would take it" This reverts commit c2ff358b5871c3909a0e99dca7ba9dd2ae785e49. --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/data.rs | 2 +- crates/engine/src/cmd/data/validation.rs | 62 ++- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/edit/paste_special.rs | 180 ++++--- crates/engine/src/cmd/formulas.rs | 147 ++++-- crates/engine/src/cmd/insert/cond_format.rs | 23 +- crates/engine/src/cmd/insert/table.rs | 47 +- crates/engine/src/cmd/pivot/tests.rs | 35 ++ crates/engine/src/cmd/sheet.rs | 144 ++++-- crates/engine/src/cmd/sheet/tabs.rs | 78 ++- crates/engine/src/tests.rs | 533 ++++++++++++++++++++ crates/engine/src/tests/objects.rs | 47 ++ crates/engine/src/tests/python_cells.rs | 15 + crates/formula/src/adjust.rs | 5 +- crates/formula/src/tests.rs | 4 + crates/model/src/features.rs | 62 +++ crates/model/src/lib.rs | 2 +- crates/model/src/workbook.rs | 232 +++++++++ docs/architecture.md | 33 +- 19 files changed, 1409 insertions(+), 244 deletions(-) diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index b4588edcef..e6b90d2512 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -34,7 +34,7 @@ use tools::split_delimited; use tools::{remove_duplicates, text_to_columns}; pub use validation::{check_validation, list_items}; use validation::{circle_invalid, validate_cmd, validation}; -pub(super) use validation::{move_rule_formula, remove_validation_cells}; +pub(super) use validation::{move_rule_formula, moved_rule_parts, remove_rule_cells, remove_validation_cells}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/data/validation.rs b/crates/engine/src/cmd/data/validation.rs index 0d86fbc360..31f40491d7 100644 --- a/crates/engine/src/cmd/data/validation.rs +++ b/crates/engine/src/cmd/data/validation.rs @@ -87,19 +87,67 @@ fn subtract_ranges(r: RangeRef, cuts: &[RangeRef]) -> Vec { out } +/// A conditional format or validation: ranges, and formulas written for their top-left cell. +pub(in super::super) trait Rule: Clone { + fn parts(&mut self) -> (&mut Vec, Vec<&mut String>); +} + +impl Rule for Validation { + fn parts(&mut self) -> (&mut Vec, Vec<&mut String>) { + let Validation { ranges, f1, f2, .. } = self; + (ranges, std::iter::once(f1).chain(f2.as_mut()).collect()) + } +} + +impl Rule for gridcraft_model::CondFormat { + fn parts(&mut self) -> (&mut Vec, Vec<&mut String>) { + (&mut self.ranges, self.rule.relative_formulas_mut()) + } +} + /// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges. /// When the rule's top-left cell goes, its relative formulas are rewritten for the new top-left /// cell, so the cells left keep checking the same cells. pub(in super::super) fn remove_validation_cells(validations: &mut Vec, cuts: &[RangeRef]) { - for dv in validations.iter_mut() { - let before = RangeRef::top_left(&dv.ranges); - dv.ranges = dv.ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).collect(); - if let (Some(from), Some(to)) = (before, RangeRef::top_left(&dv.ranges)) { - dv.f1 = move_rule_formula(&dv.f1, from, to); - dv.f2 = dv.f2.take().map(|f| move_rule_formula(&f, from, to)); + remove_rule_cells(validations, cuts); +} + +/// [`remove_validation_cells`] for any kind of rule. +pub(in super::super) fn remove_rule_cells(rules: &mut Vec, cuts: &[RangeRef]) { + for rule in rules.iter_mut() { + let (ranges, formulas) = rule.parts(); + let before = RangeRef::top_left(ranges); + *ranges = ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).collect(); + if let (Some(from), Some(to)) = (before, RangeRef::top_left(ranges)) { + for f in formulas { + *f = move_rule_formula(f, from, to); + } } } - validations.retain(|d| !d.ranges.is_empty()); + rules.retain_mut(|r| !r.parts().0.is_empty()); +} + +/// The parts of `rules` inside `block`, moved to the block at `to`, as a cut takes them with +/// its cells. Each part's formulas stay written for where its top-left cell was, as a cut +/// cell's formula is copied: the reference rewrite for the move then shifts them. +pub(in super::super) fn moved_rule_parts(rules: &[T], block: RangeRef, to: CellRef) -> Vec { + let dr = i64::from(to.row) - i64::from(block.start.row); + let dc = i64::from(to.col) - i64::from(block.start.col); + let mut out = Vec::new(); + for rule in rules { + let mut part = rule.clone(); + let (ranges, formulas) = part.parts(); + let Some(first) = RangeRef::top_left(ranges) else { continue }; + let inside: Vec = ranges.iter().filter_map(|r| r.intersection(&block)).collect(); + let Some(from) = RangeRef::top_left(&inside) else { continue }; + let moved: Vec = inside.iter().filter_map(|r| Some(RangeRef::new(r.start.offset(dr, dc)?, r.end.offset(dr, dc)?))).collect(); + for f in formulas { + *f = move_rule_formula(f, first, from); + } + *ranges = moved; + out.push(part); + } + out } pub(super) fn validation(s: &mut Session, p: &Json) -> Result { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 2ec1cb64f2..d14664a9fc 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -35,7 +35,7 @@ use go_to::go_to_special; #[cfg(test)] use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts}; use paste_special::paste_special; -pub(crate) use paste_special::{rewrite_all_formulas_many, rewrite_cell_links, rewrite_python_refs}; +pub(crate) use paste_special::{place_moved_rules, rewrite_all_formulas_many, rewrite_python_refs}; use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set}; pub fn specs() -> Vec { diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index ac1a073ecc..ad17e603df 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -79,7 +79,18 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { let cut_move = clip.cut && same_doc && what == What::All; let src_wb = clip.wb.clone(); let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) }; - let src_sheet_name = src_sheet.name.clone(); + // The source sheet's name now: a cut whose sheet was renamed after it moves its cells, + // rules and the references to them on the sheet as it is named, not as the clipboard saw it. + let src_sheet_name = match s.doc()?.wb.sheet(clip.sheet) { + Some(live) if clip.cut && same_doc => live.name.clone(), + _ => src_sheet.name.clone(), + }; + // A cut moves its block as it is, as Excel's does: it can't be transposed, tiled over a + // larger selection or pasted skipping blanks (the move's references, rules and arrays follow + // the whole block unturned, and its rules replace the destination's under every cell). + if cut_move && (transpose || skip_blanks || tiles_r > 1 || tiles_c > 1) { + return Err(EngineError::Other("The cut area can only be pasted as it is: paste it without Transpose or Skip Blanks, into one cell.".into())); + } edit(s, |cx| { // Styles from another workbook must be re-interned. let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default(); @@ -92,6 +103,9 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { }; let mut moved_formulas = std::collections::BTreeMap::new(); let mut moved_pictures = std::collections::BTreeMap::new(); + // A cut moves the rules its cells hold now, not the clipboard's: rules cleared or added + // since the cut would otherwise come back or be lost. + let live_source = if cut_move { cx.wb.sheet(clip.sheet).cloned() } else { None }; if cut_move { // Remove the source first (contents and formats), and fix references to it. let source = cx.sheet_mut(clip.sheet)?; @@ -347,7 +361,8 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } } let pasted = RangeRef::new(at, at.offset_clamped(i64::from(tiles_r * h) - 1, i64::from(tiles_c * w) - 1)); - if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) { + // A cut takes its rules along itself (`move_cut_rules`, below). + if !link && !cut_move && matches!(what, What::All | What::AllExceptBorders | What::Validation) { paste_validations(cx, src_sheet, src, dest_sheet, pasted, PasteMode { transpose, skip_blanks, skip_rows: &skip_rows })?; } if what == What::ColumnWidths { @@ -379,7 +394,8 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } } } - if cut_move { + if let Some(live) = &live_source { + move_cut_rules(cx, live, (clip.sheet, dest_sheet), src, at)?; // References elsewhere to the moved block now point to its new place. let e = if dest_sheet == clip.sheet { gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col } @@ -564,7 +580,67 @@ fn paste_validations( Ok(()) } -/// Applies a reference adjustment to every cell formula and defined name in the workbook. +/// A cut, or Move Columns, takes its cells' conditional formats and validation with it, from +/// sheet `from` to the block at `at` on sheet `to`, replacing the rules there. The moved parts' +/// formulas are handled as the moved cells' are: kept written for where their cells were (on +/// another sheet, with their references to it named), so the reference rewrite for the move +/// shifts those into the block once. `snapshot` is the source sheet before the block moved. +pub(crate) fn move_cut_rules( + cx: &mut crate::cmd::Ctx, + snapshot: &gridcraft_model::Sheet, + (from, to): (usize, usize), + src: RangeRef, + at: CellRef, +) -> Result<()> { + let mut cfs: Vec = crate::cmd::data::moved_rule_parts(&snapshot.cond_formats, src, at); + let mut dvs: Vec = crate::cmd::data::moved_rule_parts(&snapshot.validations, src, at); + if from != to { + let name = |t: &mut String| { + if let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) { + let e = e.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(snapshot.name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }); + *t = format!("{}{}", if t.starts_with('=') { "=" } else { "" }, gridcraft_formula::print(&e)); + } + }; + // Every formula, thresholds included: an unnamed reference would read the destination sheet. + cfs.iter_mut().flat_map(|r| r.rule.formulas_mut()).for_each(name); + dvs.iter_mut().flat_map(|r| r.formulas_mut()).for_each(name); + } + place_moved_rules(cx, (from, to), src, at, (cfs, dvs)) +} + +/// Takes the rules off the cells of `src` on sheet `from` and puts `parts` (the moved parts of +/// them, as [`move_cut_rules`] builds them) on the block at `at` on sheet `to`, in place of the +/// rules there. +pub(crate) fn place_moved_rules( + cx: &mut crate::cmd::Ctx, + (from, to): (usize, usize), + src: RangeRef, + at: CellRef, + (cfs, dvs): (Vec, Vec), +) -> Result<()> { + let source = cx.sheet_mut(from)?; + crate::cmd::data::remove_rule_cells(&mut source.cond_formats, &[src]); + crate::cmd::data::remove_rule_cells(&mut source.validations, &[src]); + let block = RangeRef::new(at, at.offset_clamped(i64::from(src.height()) - 1, i64::from(src.width()) - 1)); + let dest = cx.sheet_mut(to)?; + crate::cmd::data::remove_rule_cells(&mut dest.cond_formats, &[block]); + crate::cmd::data::remove_rule_cells(&mut dest.validations, &[block]); + dest.cond_formats.extend(cfs); + dest.validations.extend(dvs); + Ok(()) +} + +/// Applies a reference adjustment to every reference the workbook holds +/// ([`Workbook::rewrite_references`]) and its Python cells, and moves the legacy array ranges +/// on `target`. +/// +/// [`Workbook::rewrite_references`]: gridcraft_model::Workbook::rewrite_references pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { rewrite_all_formulas_many(wb, target, std::slice::from_ref(e)) } @@ -572,90 +648,28 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: & /// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once. pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> { use gridcraft_formula::adjust::Edit; + let adjust_all = + |host: &str, expr: gridcraft_formula::Expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)); + wb.rewrite_references(&|host, expr| adjust_all(host.name, expr)); // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too // (a cut moves its arrays itself). - let moves_arrays = |e: &Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); - for si in 0..wb.sheets.len() { - let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); - let keys: Vec<(CellRef, std::sync::Arc)> = - wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, cell)| cell.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - if keys.is_empty() { - continue; - } - let on_target = host.eq_ignore_ascii_case(target); - let Some(sheet) = wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - // Borrows the tree and copies and prints only the formulas the edits change. A formula - // the edits leave alone keeps its stored text, even if that text is not canonical. - let Some(new) = f.with_expr(|x| { - let mut cur: Option = None; - for e in edits { - if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) { - cur = Some(n); - } - } - cur - }) else { - continue; - }; - let mut array = f.array; - for e in edits { - array = match array { - Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e), - a => a, - }; - } - let nf = match new { - Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) }, - None if array != f.array => Formula { array, ..(*f).clone() }, - None => continue, - }; - if let Some(cell) = sheet.cells.get_mut(c) { - cell.formula = Some(std::sync::Arc::new(nf)); + let moves_arrays = |e: &&Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); + if edits.iter().any(|e| moves_arrays(&e)) + && let Some(si) = wb.sheet_index(target) + && let Some(sheet) = wb.sheet_mut(si) + { + let arrays: Vec<(CellRef, std::sync::Arc)> = + sheet.cells.iter().filter_map(|(c, cell)| cell.formula.clone().filter(|f| f.array.is_some()).map(|f| (c, f))).collect(); + for (c, f) in arrays { + let array = edits.iter().filter(moves_arrays).fold(f.array, |a, e| a.and_then(|a| crate::cmd::sheet::map_range(a, e))); + if array != f.array + && let Some(cell) = sheet.cells.get_mut(c) + { + cell.formula = Some(std::sync::Arc::new(Formula { array, ..(*f).clone() })); } } } - for n in wb.names.iter_mut() { - if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) { - // Names are workbook-level: unqualified refs don't occur; qualified ones adjust. - let new = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e)); - n.formula = gridcraft_formula::print(&new); - } - } - rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e))); - rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e))) -} - -/// Runs `f` over every reference a floating object holds (a chart's series values, categories, -/// name and bubble sizes, and the source block it was made from, and a form control's linked -/// cell). Every edit that moves -/// references calls it: inserting and deleting lines and cells and cut-moves (through -/// [`rewrite_all_formulas`]), and renaming and deleting sheets. `f` maps a reference held by an -/// object on the sheet named `host` to its new form; text that does not parse is kept. A source -/// block that no longer exists is dropped. -pub(crate) fn rewrite_cell_links(wb: &mut gridcraft_model::Workbook, f: impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr) { - for si in 0..wb.sheets.len() { - let Some(host) = wb.sheets.get(si).filter(|s| !s.charts.is_empty() || !s.controls.is_empty()).map(|s| s.name.clone()) else { continue }; - let Some(sh) = wb.sheet_mut(si) else { continue }; - let fix = |text: &str| -> String { - match gridcraft_formula::parse(text) { - Ok(expr) => gridcraft_formula::print(&f(&host, expr)), - Err(_) => text.to_string(), - } - }; - for ch in sh.charts.iter_mut() { - ch.source = ch.source.as_deref().map(fix).filter(|s| !s.contains("#REF!")); - for se in ch.series.iter_mut() { - se.values = fix(&se.values); - se.categories = se.categories.as_deref().map(fix); - se.name = se.name.as_deref().map(fix); - se.bubble_sizes = se.bubble_sizes.as_deref().map(fix); - } - } - for c in sh.controls.iter_mut() { - c.link = c.link.as_deref().map(fix); - } - } + rewrite_python_refs(wb, &adjust_all) } /// Rewrites the `xl("…")` literals in every Python cell with `f`, which maps a reference held on diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index 6afd147686..7b2e2732ff 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -1,7 +1,7 @@ //! Formulas tab: AutoSum, Insert Function, names, auditing, calculation. use gridcraft_core::{CellError, CellRef, RangeRef, Value}; -use gridcraft_model::{CalcMode, Cell, DefinedName, Formula, Workbook}; +use gridcraft_model::{CalcMode, Cell, DefinedName, Workbook}; use serde_json::{Value as Json, json}; use super::{ @@ -408,10 +408,12 @@ fn define_name(s: &mut Session, p: &Json) -> Result { }; edit(s, |cx| { if let Some((old_name, old_scope)) = &old { - cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope)); + // Formulas are renamed while the old name is still defined, so a chart series named + // by it is still read as a reference. if !old_name.eq_ignore_ascii_case(&name) { - rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name); + rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name)?; } + cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope)); } cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && n.scope == scope)); cx.wb.names.push(DefinedName { name: name.clone(), scope, formula: refers.clone(), comment: comment.clone(), hidden: false }); @@ -420,49 +422,124 @@ fn define_name(s: &mut Session, p: &Json) -> Result { }) } -/// Formulas that use a renamed name follow it: cell formulas and other names' definitions, on +/// References to a renamed name follow it: every one the workbook holds +/// ([`gridcraft_model::Workbook::rewrite_references`]) and Python cells' `xl()` references, on /// the sheets where `old` resolves to the renamed name (its own sheet for a sheet-scoped name; /// every sheet without a same-named sheet-level name for a workbook-level one). -fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option, new: &str) { +fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option, new: &str) -> Result<()> { let shadowed: Vec = wb.names.iter().filter(|n| n.name.eq_ignore_ascii_case(old)).filter_map(|n| n.scope).collect(); let applies = |sheet: usize| match old_scope { Some(s) => s == sheet, None => !shadowed.contains(&sheet), }; - // The renamed expression, or `None` when the name doesn't occur in it. + // Set when an occurrence would be captured by a LET or LAMBDA local of the new name. + let captured = std::cell::Cell::new(false); let rename = |e: gridcraft_formula::Expr| { - let mut hit = false; - let out = e.map(&mut |x| match x { - gridcraft_formula::Expr::Name(n) if n.eq_ignore_ascii_case(old) => { - hit = true; - gridcraft_formula::Expr::Name(new.to_string()) - } - o => o, - }); - hit.then_some(out) + let mut bound = Vec::new(); + rename_free_name(e, old, new, &mut bound, &captured, 0) }; - for i in 0..wb.sheets.len() { - if !applies(i) { - continue; - } - let Some(sh) = wb.sheet_mut(i) else { continue }; - let formulas: Vec<(CellRef, std::sync::Arc)> = sh.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect(); - for (c, f) in formulas { - let Some(e) = f.expr().and_then(rename) else { continue }; - let mut nf = Formula::from_expr(e); - nf.array = f.array; - nf.dynamic = f.dynamic; - if let Some(cell) = sh.cells.get_mut(c) { - cell.formula = Some(std::sync::Arc::new(nf)); - } - } + // Every reference held where the renamed name is the one meant: on its sheet (or, for a + // workbook name, every sheet without one of its own), and in workbook names. + wb.rewrite_references(&|host, e| if host.sheet.is_none_or(applies) { rename(e) } else { e }); + // Python cells' `xl("…")` references too. + let sheet_of: std::collections::HashMap = wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); + crate::cmd::edit::rewrite_python_refs(wb, &|host, e| { + if sheet_of.get(&host.to_ascii_lowercase()).copied().is_none_or(applies) { rename(e) } else { e } + })?; + if captured.get() { + return Err(EngineError::Other(format!( + "The name can't be changed to {new}: a LET or LAMBDA in a formula that uses it already has a local name {new}." + ))); } - for n in wb.names.iter_mut() { - if n.scope.is_none_or(applies) - && let Some(e) = gridcraft_formula::parse_name(&n.formula).ok().and_then(rename) - { - n.formula = gridcraft_formula::print(&e); + Ok(()) +} + +/// `e` with every free occurrence of the name `old` renamed to `new`. A LET or LAMBDA local is not +/// the defined name, so its own occurrences (of `old`) are left alone, and a free occurrence +/// inside the scope of a local named `new` would be captured by it: that sets `captured`. `bound` +/// holds the locals in scope. Nesting deeper than any formula the parser accepts is left as it is. +fn rename_free_name( + e: gridcraft_formula::Expr, + old: &str, + new: &str, + bound: &mut Vec, + captured: &std::cell::Cell, + depth: usize, +) -> gridcraft_formula::Expr { + use gridcraft_formula::Expr; + const MAX_DEPTH: usize = 512; + if depth > MAX_DEPTH { + return e; + } + let is_bound = |bound: &[String], n: &str| bound.iter().any(|b| b.eq_ignore_ascii_case(n)); + let walk = |e: Expr, bound: &mut Vec| rename_free_name(e, old, new, bound, captured, depth + 1); + match e { + Expr::Name(n) if n.eq_ignore_ascii_case(old) && !is_bound(bound, &n) => { + if is_bound(bound, new) { + captured.set(true); + } + Expr::Name(new.to_string()) } + Expr::Call(name, args) if name == "LET" && args.len() >= 3 && !args.len().is_multiple_of(2) => { + let saved = bound.len(); + let mut args = args; + // The arguments are odd in number: pairs of a declaration and its value, then the body. + let body = args.pop(); + let mut out = Vec::with_capacity(args.len() + 1); + let mut pairs = args.into_iter(); + while let (Some(declaration), Some(value)) = (pairs.next(), pairs.next()) { + // A value comes before its own local is in scope; the declaration is the local's + // own name, never the defined name. + let value = walk(value, bound); + if let Expr::Name(n) = &declaration { + bound.push(n.clone()); + } + out.push(declaration); + out.push(value); + } + out.extend(body.map(|b| walk(b, bound))); + bound.truncate(saved); + Expr::Call(name, out) + } + Expr::Call(name, args) if name == "LAMBDA" => { + let saved = bound.len(); + let last = args.len().saturating_sub(1); + let mut out = Vec::with_capacity(args.len()); + for (i, arg) in args.into_iter().enumerate() { + if i == last { + out.push(walk(arg, bound)); + } else { + if let Expr::Name(n) = &arg { + bound.push(n.clone()); + } + out.push(arg); + } + } + bound.truncate(saved); + Expr::Call(name, out) + } + Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| walk(a, bound)).collect()), + Expr::Invoke(callee, args) => Expr::Invoke(Box::new(walk(*callee, bound)), args.into_iter().map(|a| walk(a, bound)).collect()), + Expr::Array(rows) => Expr::Array(rows.into_iter().map(|r| r.into_iter().map(|x| walk(x, bound)).collect()).collect()), + Expr::Unary(op, x) => Expr::Unary(op, Box::new(walk(*x, bound))), + Expr::Binary(op, a, b) => { + // A long operator chain is unwound, not recursed into once per operand (as + // `Expr::map` does), so its length doesn't count toward the nesting limit. + let mut spine = vec![(op, b)]; + let mut node = *a; + while let Expr::Binary(op, a, b) = node { + spine.push((op, b)); + node = *a; + } + let mut acc = walk(node, bound); + while let Some((op, b)) = spine.pop() { + let b = walk(*b, bound); + acc = Expr::Binary(op, Box::new(acc), Box::new(b)); + } + acc + } + Expr::Paren(x) => Expr::Paren(Box::new(walk(*x, bound))), + other => other, } } diff --git a/crates/engine/src/cmd/insert/cond_format.rs b/crates/engine/src/cmd/insert/cond_format.rs index 0ce4bbf2c1..6f0928ab55 100644 --- a/crates/engine/src/cmd/insert/cond_format.rs +++ b/crates/engine/src/cmd/insert/cond_format.rs @@ -1,7 +1,7 @@ use super::{ - Anchor, BorderLine, BorderStyle, Borders, CellRef, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result, - Session, Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges, - target_sheet, u32_param, + Anchor, BorderLine, BorderStyle, Borders, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result, Session, + Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges, target_sheet, + u32_param, }; #[cfg(test)] @@ -282,7 +282,9 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result { // The relative formulas are written for the top-left cell: when it goes, they're // rewritten for the new one, so the areas left keep reading the same cells. if let (Some(from), Some(to)) = (before, RangeRef::top_left(&cf.ranges)) { - rebase_cf_formulas(&mut cf.rule, from, to); + for f in cf.rule.relative_formulas_mut() { + *f = crate::cmd::data::move_rule_formula(f, from, to); + } } } sh.cond_formats.retain(|c| !c.ranges.is_empty()); @@ -291,19 +293,6 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result { }) } -/// Moves the relative references of a rule's per-cell formulas written for `from` to `to`. -fn rebase_cf_formulas(rule: &mut CfRule, from: CellRef, to: CellRef) { - let mv = |f: &str| crate::cmd::data::move_rule_formula(f, from, to); - match rule { - CfRule::CellIs { a, b, .. } => { - *a = mv(a); - *b = b.as_deref().map(mv); - } - CfRule::Expression { formula, .. } => *formula = mv(formula), - _ => {} - } -} - pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result { let sheet = target_sheet(s, p)?; if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() { diff --git a/crates/engine/src/cmd/insert/table.rs b/crates/engine/src/cmd/insert/table.rs index 068c5ddf9b..2a517766c4 100644 --- a/crates/engine/src/cmd/insert/table.rs +++ b/crates/engine/src/cmd/insert/table.rs @@ -293,28 +293,39 @@ pub(super) fn table_rename(s: &mut Session, p: &Json) -> Result { if let Some(t) = cx.sheet_mut(si)?.tables.get_mut(ti) { t.name = name.clone(); } - // Structured references follow the rename. + // Every reference to the table follows the rename. A bare name that is also a defined + // name where it is held resolves to the defined name, so it is not the table; in a + // workbook name, that is a workbook-level defined name. + let shadowed: Vec = (0..cx.wb.sheets.len()).map(|i| cx.wb.name(&old, i).is_some()).collect(); + let shadowed_in_book = cx.wb.names.iter().any(|n| n.scope.is_none() && n.name.eq_ignore_ascii_case(&old)); + let sheet_of: std::collections::HashMap = + cx.wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); + let rename = |sheet: Option, e: gridcraft_formula::Expr| { + let shadow = sheet.map_or(shadowed_in_book, |i| shadowed.get(i).copied().unwrap_or(false)); + e.map(&mut |x| match x { + gridcraft_formula::Expr::Struct(mut st) if st.table.eq_ignore_ascii_case(&old) => { + st.table = name.clone(); + gridcraft_formula::Expr::Struct(st) + } + gridcraft_formula::Expr::Name(n) if !shadow && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()), + o => o, + }) + }; + cx.wb.rewrite_references(&|host, e| rename(host.sheet, e)); + // A bare PivotTable source binds to a table before a defined name (`pivot::resolve_source`), + // so a defined name with the old name doesn't shadow it: it follows the rename regardless. for i in 0..cx.wb.sheets.len() { - let keys: Vec<(CellRef, std::sync::Arc)> = - cx.wb.sheets.get(i).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - // A bare name that is also a defined name resolves to the defined name, so it is not the table. - let shadowed = cx.wb.name(&old, i).is_some(); - let Some(sh) = cx.wb.sheet_mut(i) else { continue }; - for (c, f) in keys { - let Some(e) = f.expr() else { continue }; - let ne = e.map(&mut |x| match x { - gridcraft_formula::Expr::Struct(mut st) if st.table.eq_ignore_ascii_case(&old) => { - st.table = name.clone(); - gridcraft_formula::Expr::Struct(st) - } - gridcraft_formula::Expr::Name(n) if !shadowed && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()), - o => o, - }); - if let Some(cell) = sh.cells.get_mut(c) { - cell.formula = Some(std::sync::Arc::new(Formula::from_expr(ne))); + let names_old = |src: &str| src.trim().trim_start_matches('=').trim().eq_ignore_ascii_case(&old); + if !cx.wb.sheet(i).is_some_and(|sh| sh.pivots.iter().any(|pt| names_old(&pt.source))) { + continue; + } + for pt in &mut cx.sheet_mut(i)?.pivots { + if names_old(&pt.source) { + pt.source = name.clone(); } } } + crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|host, e| rename(sheet_of.get(&host.to_ascii_lowercase()).copied(), e))?; cx.structural = true; Ok(Json::Null) }) diff --git a/crates/engine/src/cmd/pivot/tests.rs b/crates/engine/src/cmd/pivot/tests.rs index 03f2d7a5f6..93ad9868cf 100644 --- a/crates/engine/src/cmd/pivot/tests.rs +++ b/crates/engine/src/cmd/pivot/tests.rs @@ -1428,3 +1428,38 @@ fn legacy_count_numbers_caption_follows_the_function() { assert_eq!(text(&s, "E3"), after, "{legacy}"); } } + +/// A defined name with a table's name doesn't stop a PivotTable's table source following a rename +/// of the table: a bare source binds to the table first. +#[test] +fn a_table_rename_moves_a_pivot_source_a_defined_name_shadows() { + let mut s = sales(); + s.execute("insert.table", json!({"range": "A1:E13"})).unwrap(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap(); + assert_eq!(pt(&s).source, "Table1"); + s.execute("formulas.defineName", json!({"name": "Table1", "refersTo": "=Sheet1!$A$1:$B$3"})).unwrap(); + s.execute("table.rename", json!({"table": "Table1", "name": "Data"})).unwrap(); + assert_eq!(pt(&s).source, "Data"); + s.execute("pivot.refresh", json!({})).unwrap(); + let gt = find_row(&s, "Grand Total").unwrap(); + assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0)); +} + +/// A PivotTable source that is a table's name reads the table before a defined name of that name, +/// so renaming the defined name leaves it on the table; a source that is the defined name's own +/// follows the rename. +#[test] +fn renaming_a_defined_name_leaves_a_table_source_on_its_table() { + let mut s = sales(); + s.execute("insert.table", json!({"range": "A1:E13", "name": "Data"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Data", "refersTo": "=Sheet1!$A$1:$E$3"})).unwrap(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap(); + assert_eq!(pt(&s).source, "Data"); + s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Data", "refersTo": "=Sheet1!$A$1:$E$3"})).unwrap(); + assert_eq!(pt(&s).source, "Data"); + s.execute("pivot.refresh", json!({})).unwrap(); + let gt = find_row(&s, "Grand Total").unwrap(); + assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0)); +} diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index bde0c50590..d0d1ed6235 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -154,7 +154,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: } sh.merges = sh.merges.iter().filter_map(|m| map_range(*m)).filter(|m| !m.is_single()).collect(); for cf in sh.cond_formats.iter_mut() { - cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r)).collect(); + let before = std::mem::take(&mut cf.ranges); + let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r).map(|m| (*r, m))).collect(); + cf.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(cf.rule.relative_formulas_mut(), &before, &moves, &e); } for er in sh.edit_ranges.iter_mut() { er.ranges = er.ranges.iter().filter_map(|r| map_range(*r)).collect(); @@ -162,7 +165,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: sh.edit_ranges.retain(|er| !er.ranges.is_empty()); sh.cond_formats.retain(|cf| !cf.ranges.is_empty()); for dv in sh.validations.iter_mut() { - dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r)).collect(); + let before = std::mem::take(&mut dv.ranges); + let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r).map(|m| (*r, m))).collect(); + dv.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(dv.formulas_mut(), &before, &moves, &e); } sh.validations.retain(|dv| !dv.ranges.is_empty()); for t in sh.tables.iter_mut() { @@ -239,8 +245,7 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: } } -/// Rewrites every formula reference (chart series included), sparkline source and PivotTable -/// source for a structural edit on `target`. +/// Rewrites every reference the workbook holds for a structural edit on `target`. pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> { rewrite_many(cx, target, std::slice::from_ref(e)) } @@ -248,34 +253,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> { /// [`rewrite`] for several edits applied in order, parsing each reference once. fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> { cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone()))); - let wb = &mut cx.wb; - super::edit::rewrite_all_formulas_many(wb, target, edits)?; - for si in 0..wb.sheets.len() { - let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); - let Some(sh) = wb.sheet_mut(si) else { continue }; - let fix = |text: &str| -> String { - match gridcraft_formula::parse(text) { - Ok(expr) => gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))), - Err(_) => text.to_string(), - } - }; - for sp in sh.sparklines.iter_mut() { - sp.source = fix(&sp.source); - } - // PivotTable sources (a range, table or defined name) are only rewritten when the edit - // moves them, so table and name sources keep their text. - for pt in sh.pivots.iter_mut() { - let body = pt.source.trim().trim_start_matches('='); - if let Ok(expr) = gridcraft_formula::parse(body) { - let before = gridcraft_formula::print(&expr); - let after = gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))); - if after != before { - pt.source = after; - } - } - } - } - Ok(()) + super::edit::rewrite_all_formulas_many(&mut cx.wb, target, edits) } /// Inserting or deleting cells moves the copied block away from the stored source range, so, like @@ -442,15 +420,37 @@ fn move_columns(s: &mut Session, p: &Json) -> Result { let out = edit(s, |cx| { let name = cx.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default(); cx.protection_checked = true; + // The moved columns' rules go with them as a cut's do, so a rule wider than them stays on + // its other cells and checks what it did. Their parts are taken from the sheet before the + // columns are made room for: a rule's formulas are written for its top-left cell, and + // after the insert they no longer say what the moved cells read (a reference between the + // rule's top-left and the moved columns has moved, the top-left has not). + let insert = Edit::Insert { axis: Axis::Cols, at: before, count }; + let original = cx.wb.sheets.get(sheet).cloned().ok_or_else(|| bad("sheet.moveColumns", "no such sheet"))?; + let at = CellRef::new(0, destination); + let block = RangeRef::cols(from, end - 1); + let mut cfs: Vec = crate::cmd::data::moved_rule_parts(&original.cond_formats, block, at); + let mut dvs: Vec = crate::cmd::data::moved_rule_parts(&original.validations, block, at); + // Each part's formulas, written for the moved cells where they stood, follow the insert + // as those cells' formulas do; the move and delete below then rewrite them in place. + let follow_insert = |t: &mut String| { + if let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) { + let e = gridcraft_formula::adjust::adjust(e, &name, &name, &insert); + *t = format!("{}{}", if t.starts_with('=') { "=" } else { "" }, gridcraft_formula::print(&e)); + } + }; + cfs.iter_mut().flat_map(|r| r.rule.formulas_mut()).for_each(follow_insert); + dvs.iter_mut().flat_map(|r| r.formulas_mut()).for_each(follow_insert); { let sh = cx.sheet_mut(sheet)?; sh.cells.shift_cols(before, count as i64); shift_sheet_features(sh, Axis::Cols, before, count, true); } - rewrite(cx, &name, &Edit::Insert { axis: Axis::Cols, at: before, count })?; + rewrite(cx, &name, &insert)?; let mut touched = Vec::new(); + crate::cmd::edit::place_moved_rules(cx, (sheet, sheet), source, at, (cfs, dvs))?; { let sh = cx.sheet_mut(sheet)?; let pictures: Vec<_> = @@ -458,6 +458,7 @@ fn move_columns(s: &mut Session, p: &Json) -> Result { let cells = sh.take_cells(source); let moved_lines: Vec<_> = (0..count).filter_map(|offset| sh.cols.remove(&(moved_from + offset)).map(|info| (offset, info))).collect(); let movement = Edit::Move { from: source, to_row: 0, to_col: destination }; + // (Its conditional formats and validation no longer touch the moved columns.) shift_cell_features(sh, &movement); for object in sh .charts @@ -752,13 +753,83 @@ pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option { } } +/// A conditional format's or validation's formulas are written for its ranges' top-left cell. +/// When an edit moves its ranges (`moves`: each range before and after) so the top-left is +/// another cell, they are re-hosted at that cell where it stood before the edit; rewriting the +/// workbook's references for the edit then moves them as it moves a formula there. A range +/// moved whole keeps its cells in step, so its top-left stood where the range's offset says; +/// one cut short (its first cells deleted), or one whose own cells an insert or delete of cells +/// shifted only in part into its top-left, takes the cell that moved into its place. +/// `before` is every range the rule had before the edit (the formulas are written for their +/// top-left cell, which may lie in a range the edit removed). +fn rehost_rule(formulas: Vec<&mut String>, before: &[RangeRef], moves: &[(RangeRef, RangeRef)], e: &Edit) { + let (Some(from), Some(to)) = (RangeRef::top_left(before), RangeRef::top_left(&moves.iter().map(|(_, m)| *m).collect::>())) else { + return; + }; + let whole = |(r, m): &(RangeRef, RangeRef)| r.width() == m.width() && r.height() == m.height(); + let back = |c: CellRef, (r, m): &(RangeRef, RangeRef)| { + CellRef::new( + (i64::from(c.row) - i64::from(m.start.row) + i64::from(r.start.row)).max(0) as u32, + (i64::from(c.col) - i64::from(m.start.col) + i64::from(r.start.col)).max(0) as u32, + ) + }; + let holder = moves.iter().find(|(_, m)| m.contains(to)); + let same_shift = moves.iter().all(whole) + && moves.windows(2).all(|w| match w { + [a, b] => back(to, a) == back(to, b), + _ => true, + }); + // Inserting or deleting cells can shift part of a range and keep its size (cells deleted in + // its first column only, say): when the cell the shift put at its top-left was one of the + // rule's own cells, the formulas follow that cell. + let shifted_in = matches!(e, Edit::InsertCells { .. } | Edit::DeleteCells { .. }) + .then(|| pre_image(e, to)) + .filter(|p| *p != to && before.iter().any(|r| r.contains(*p))); + let at = match holder { + Some(_) if shifted_in.is_some() => shifted_in.unwrap_or(to), + Some(p) if whole(p) => back(to, p), + Some(_) => pre_image(e, to), + None if same_shift => moves.first().map_or(to, |p| back(to, p)), + None => pre_image(e, to), + }; + if at != from { + for f in formulas { + *f = crate::cmd::data::move_rule_formula(f, from, at); + } + } +} + +/// Where the cell that `e` puts at `c` stood before it (`c` itself when nothing moved it). +fn pre_image(e: &Edit, c: CellRef) -> CellRef { + let (axis, count) = match *e { + Edit::Insert { axis, count, .. } | Edit::Delete { axis, count, .. } => (axis, count), + Edit::InsertCells { axis, range } | Edit::DeleteCells { axis, range } => { + (axis, if axis == Axis::Rows { range.height() } else { range.width() }) + } + // A move takes ranges whole, which `rehost_rule` handles by their offset. + Edit::Move { .. } | Edit::MoveToSheet { .. } => return c, + }; + let along = |d: i64| match axis { + Axis::Rows => c.offset(d, 0), + Axis::Cols => c.offset(0, d), + }; + [Some(c), along(i64::from(count)), along(-i64::from(count))] + .into_iter() + .flatten() + .find(|p| map_range(RangeRef::cell(*p), e).map(|r| r.start) == Some(c)) + .unwrap_or(c) +} + /// Shifts what Insert/Delete Cells moves along with the cells: merged areas, conditional /// format, validation, table, filter and print-area ranges, notes, links and sparklines. pub(super) fn shift_cell_features(sh: &mut Sheet, e: &Edit) { let map_cell = |c: CellRef| map_range(RangeRef::cell(c), e).map(|r| r.start); sh.merges = sh.merges.iter().filter_map(|m| map_range(*m, e)).filter(|m| !m.is_single()).collect(); for cf in sh.cond_formats.iter_mut() { - cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r, e)).collect(); + let before = std::mem::take(&mut cf.ranges); + let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r, e).map(|m| (*r, m))).collect(); + cf.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(cf.rule.relative_formulas_mut(), &before, &moves, e); } for er in sh.edit_ranges.iter_mut() { er.ranges = er.ranges.iter().filter_map(|r| map_range(*r, e)).collect(); @@ -766,7 +837,10 @@ pub(super) fn shift_cell_features(sh: &mut Sheet, e: &Edit) { sh.edit_ranges.retain(|er| !er.ranges.is_empty()); sh.cond_formats.retain(|cf| !cf.ranges.is_empty()); for dv in sh.validations.iter_mut() { - dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r, e)).collect(); + let before = std::mem::take(&mut dv.ranges); + let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r, e).map(|m| (*r, m))).collect(); + dv.ranges = moves.iter().map(|(_, m)| *m).collect(); + rehost_rule(dv.formulas_mut(), &before, &moves, e); } sh.validations.retain(|dv| !dv.ranges.is_empty()); for t in sh.tables.iter_mut() { diff --git a/crates/engine/src/cmd/sheet/tabs.rs b/crates/engine/src/cmd/sheet/tabs.rs index 2c1657ef90..77852566c5 100644 --- a/crates/engine/src/cmd/sheet/tabs.rs +++ b/crates/engine/src/cmd/sheet/tabs.rs @@ -1,4 +1,4 @@ -use super::{Arc, CellRef, Ctx, EngineError, Json, Result, Session, Sheet, Visibility, bad, bool_param, edit, json, ok, str_param, target_sheet}; +use super::{Arc, Ctx, EngineError, Json, Result, Session, Sheet, Visibility, bad, bool_param, edit, json, ok, str_param, target_sheet}; pub(super) fn insert_sheet(s: &mut Session, p: &Json) -> Result { if s.doc()?.wb.protected_structure { @@ -50,37 +50,16 @@ pub(super) fn delete_sheet(s: &mut Session, p: &Json) -> Result { let d = s.doc_mut()?; edit_doc(d, |cx| { cx.wb.sheets.remove(i); - for si in 0..cx.wb.sheets.len() { - let keys: Vec<(CellRef, Arc)> = - cx.wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - let Some(sh) = cx.wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - // Only formulas whose tree changes are rewritten; the others keep their text. - let changed = f.with_expr(|e| Some(gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order)).filter(|ne| ne != e)); - if let Some(Some(ne)) = changed - && let Some(cell) = sh.cells.get_mut(c) - { - cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne))); - } - } - } - crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?; - // Chart series into the deleted sheet become #REF!, like formulas. - crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order)); cx.wb.names.retain(|n| n.scope != Some(i)); + // Every reference into the deleted sheet becomes #REF!. + cx.wb.rewrite_references(&|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order)); + crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?; for n in cx.wb.names.iter_mut() { if let Some(sc) = n.scope.as_mut() && *sc > i { *sc -= 1; } - // Names referring to the sheet become #REF!. - if let Ok(e) = gridcraft_formula::parse_name(&n.formula) { - let ne = gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order); - if ne != e { - n.formula = gridcraft_formula::print(&ne); - } - } } if cx.wb.active_sheet() >= cx.wb.sheets.len() || cx.wb.active_sheet() > i { cx.wb.set_active_sheet(cx.wb.active_sheet().saturating_sub(1).min(cx.wb.sheets.len().saturating_sub(1))); @@ -105,21 +84,17 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result { edit(s, |cx| { let old = cx.wb.sheet(i).map(|s| s.name.clone()).unwrap_or_default(); cx.sheet_mut(i)?.name = name.clone(); + // Every reference the workbook holds follows the sheet. + cx.wb.rewrite_references(&|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name)); + // A PivotChart follows its PivotTable's sheet. Only a sheet holding such a chart is + // copied, so the others stay shared with undo snapshots. + let on_old = |link: Option<&str>| link.and_then(crate::pivot::parse_chart_link).is_some_and(|(sheet, _)| sheet.eq_ignore_ascii_case(&old)); for si in 0..cx.wb.sheets.len() { - let keys: Vec<(CellRef, Arc)> = - cx.wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - let Some(sh) = cx.wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - // Compares trees, so unchanged formulas are not printed; they keep their text. - let changed = f.with_expr(|e| Some(gridcraft_formula::adjust::rename_sheet(e.clone(), &old, &name)).filter(|ne| ne != e)); - if let Some(Some(ne)) = changed - && let Some(cell) = sh.cells.get_mut(c) - { - cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne))); - } + if !cx.wb.sheets.get(si).is_some_and(|sh| sh.charts.iter().any(|ch| on_old(ch.pivot.as_deref()))) { + continue; } + let Some(sh) = cx.wb.sheet_mut(si) else { continue }; for ch in sh.charts.iter_mut() { - // A PivotChart follows its PivotTable's sheet. if let Some((sheet, pivot)) = ch.pivot.as_deref().and_then(crate::pivot::parse_chart_link) && sheet.eq_ignore_ascii_case(&old) { @@ -127,12 +102,6 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result { } } } - crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name)); - for n in cx.wb.names.iter_mut() { - if let Ok(e) = gridcraft_formula::parse_name(&n.formula) { - n.formula = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &old, &name)); - } - } crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name))?; cx.structural = true; Ok(Json::Null) @@ -164,6 +133,29 @@ pub(super) fn move_sheet(s: &mut Session, p: &Json) -> Result { .find(|nm| cx.wb.sheet_index(nm).is_none()) .unwrap_or(base.clone()); sh.name = name; + // A copied sheet's charts plot the copy's own data, as Excel's do (its formulas keep + // what they name). + // Text that names no other sheet is kept as written (a leading `=` included). + let copy = sh.name.clone(); + let fix = |t: &mut String| { + let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) else { return }; + let before = gridcraft_formula::print(&e); + let after = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &base, ©)); + if after != before { + *t = if t.starts_with('=') { format!("={after}") } else { after }; + } + }; + for ch in &mut sh.charts { + for se in &mut ch.series { + fix(&mut se.values); + for t in [&mut se.categories, &mut se.name, &mut se.bubble_sizes].into_iter().flatten() { + fix(t); + } + } + if let Some(t) = ch.source.as_mut() { + fix(t); + } + } sh.tables.clear(); // table names must be unique sh.preserved = None; // kept file content (form controls, OLE objects…) stays with the original // Object ids are unique across the workbook (selection and the `{kind, id}` commands diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 569e8a0230..785e68f6b9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -155,6 +155,65 @@ fn editing_a_name_renames_it_in_formulas() { assert!(s.execute("formulas.defineName", json!({"name": "X", "oldName": "Missing"})).is_err()); } +/// A LET or LAMBDA local is not the defined name: renaming the name leaves a local of the same +/// name alone, in cells and in rules. +#[test] +fn renaming_a_name_leaves_let_and_lambda_locals_alone() { + let mut s = s(); + s.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=2"})).unwrap(); + s.execute("cell.set", json!({"cell": "A1", "input": "=LET(Rate, 3, Rate*10)+Rate"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=LAMBDA(Rate, Rate+1)(Rate)"})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "B1:B3", "rule": {"type": "expression", "formula": "=LET(Rate, 1, Rate) formula.trim_start_matches('=').to_string(), + other => panic!("{other:?}"), + }; + assert_eq!(rule, "LET(Rate,1,Rate)0"})).unwrap(); + let before = s.doc().unwrap().wb.clone(); + let err = s.execute("formulas.defineName", json!({"name": "Total", "refersTo": "=2", "oldName": "Rate"})); + assert!(err.is_err(), "the LET local would capture the renamed name"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &before) || *s.doc().unwrap().wb == *before); + assert_eq!(s.doc().unwrap().wb.names[0].name, "Rate"); + assert_eq!(s.doc().unwrap().wb.sheets[0].validations[0].f1.trim_start_matches('='), "LET(Total, 1, Rate*Total)>0"); +} + +/// A sheet-level name's unqualified references are read on its sheet, so they move with edits +/// there, and stay put for edits on other sheets. +#[test] +fn a_sheet_level_name_follows_edits_on_its_sheet() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Other", "before": 1})).unwrap(); + s.execute("range.setValues", json!({"range": "Sheet1!A2", "values": [[5]]})).unwrap(); + s.execute("formulas.defineName", json!({"name": "LocalRef", "refersTo": "=$A$2", "scope": "Sheet1"})).unwrap(); + let formula = |s: &Session| s.doc().unwrap().wb.names.iter().find(|n| n.name == "LocalRef").unwrap().formula.clone(); + s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Other"})).unwrap(); + assert_eq!(formula(&s), "$A$2"); + s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap(); + assert_eq!(formula(&s), "$A$3"); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": "=LocalRef"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::number(5.0)); +} + #[test] fn chart_recommendations_follow_the_data_shape() { // #215: Recommended Charts lists chart types for the data; programmatic insert stays dialog-free. @@ -2143,6 +2202,20 @@ fn table_rename_keeps_a_defined_name_with_the_same_name() { assert_eq!((v(&s, "E1"), v(&s, "F1")), (Value::Number(100.0), Value::Number(7.0))); } +/// A workbook name that reads a same-named workbook name keeps reading it when the table is renamed. +#[test] +fn table_rename_keeps_a_workbook_name_reading_a_same_named_name() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Qty"], [7]]})).unwrap(); + s.execute("cell.set", json!({"cell": "D1", "input": "100"})).unwrap(); + s.execute("insert.table", json!({"range": "A1:A2", "header": true, "name": "Data"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Data", "refersTo": "=Sheet1!$D$1"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Twice", "refersTo": "=Data*2"})).unwrap(); + s.execute("table.rename", json!({"table": "Data", "name": "Later"})).unwrap(); + let twice = s.doc().unwrap().wb.names.iter().find(|n| n.name == "Twice").map(|n| n.formula.clone()); + assert_eq!(twice.as_deref(), Some("Data*2")); +} + #[test] fn table_names_are_limited_to_255_characters() { let mut s = s(); @@ -3929,6 +4002,41 @@ fn switch_row_column_follows_inserted_and_deleted_lines() { assert_eq!(s.doc().unwrap().wb.active().unwrap().charts[0].source, None); } +/// Sets the first chart's source on Sheet1 as a file might have left it. +fn set_chart_source(s: &mut Session, source: &str) { + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + wb.sheet_mut(0).unwrap().charts[0].source = Some(source.into()); +} + +#[test] +fn a_chart_source_already_broken_survives_an_unrelated_edit() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["", "Q1", "Q2"], ["North", 1, 2], ["South", 3, 4]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "column", "at": "F1"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=Sheet1!$A$1"})).unwrap(); + set_chart_source(&mut s, "#REF!"); + // A series reads the name, so the rename rewrites this chart; the source it doesn't use is + // left broken as it was. + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + wb.sheet_mut(0).unwrap().charts[0].series[0].values = "=Rate".into(); + s.execute("formulas.defineName", json!({"name": "Fee", "oldName": "Rate", "refersTo": "=Sheet1!$A$1"})).unwrap(); + let chart = s.doc().unwrap().wb.sheet(0).unwrap().charts[0].clone(); + assert_eq!(chart.series[0].values, "=Fee"); + assert_eq!(chart.source.as_deref(), Some("#REF!")); +} + +#[test] +fn deleting_a_chart_source_sheet_drops_the_source() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["", "Q1", "Q2"], ["North", 1, 2], ["South", 3, 4]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "column", "at": "F1"})).unwrap(); + s.execute("home.insertSheet", json!({})).unwrap(); + set_chart_source(&mut s, "Sheet2!A1:C3"); + // The edit breaks the source, so it goes. + s.execute("home.deleteSheet", json!({"sheet": "Sheet2"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().charts[0].source, None); +} + #[test] fn ink_strokes_and_ink_to_shape() { let mut s = s(); @@ -7089,6 +7197,431 @@ fn pivot_new_sheet_destination_respects_workbook_structure_protection() { assert!(s.execute("insert.pivotTable", json!({"source": "A1:B3", "location": "New"})).is_err()); } +/// Renaming a sheet renames a PivotTable's source to it, and the PivotTable still refreshes. +#[test] +fn sheet_rename_renames_a_pivot_source() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Region", "Sales"], ["East", 1], ["West", 2]]})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$3", "destination": "Sheet1!E3", "rows": ["Region"], "values": ["Sales"]})) + .unwrap(); + s.execute("sheet.rename", json!({"name": "Data"})).unwrap(); + let wb = &s.doc().unwrap().wb; + assert_eq!(wb.sheets[0].pivots[0].source, "Data!$A$1:$B$3"); + s.execute("pivot.refresh", json!({})).unwrap(); +} + +/// A defined name's references are on no sheet, whatever a sheet is called: inserting rows on +/// a sheet named with a control character leaves a name's unqualified reference alone. +#[test] +fn names_are_on_no_sheet_whatever_the_sheet_is_called() { + let mut s = s(); + s.execute("formulas.defineName", json!({"name": "Nm", "refersTo": "=$A$1"})).unwrap(); + let before = s.doc().unwrap().wb.names.iter().find(|n| n.name == "Nm").map(|n| n.formula.clone()); + s.execute("sheet.rename", json!({"sheet": 0, "name": "\u{0}"})).unwrap(); + s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap(); + let after = s.doc().unwrap().wb.names.iter().find(|n| n.name == "Nm").map(|n| n.formula.clone()); + assert!(before.is_some()); + assert_eq!(before, after); +} + +/// Renaming a sheet copies only the sheets whose references change: a sheet that doesn't name +/// it stays shared with the undo snapshot. +#[test] +fn sheet_rename_leaves_untouched_sheets_shared() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("home.insertSheet", json!({"name": "Third"})).unwrap(); + s.execute("cell.set", json!({"cell": "Other!A1", "input": "=Sheet1!A1+1"})).unwrap(); + // A constant: the full recalculation after a rename writes every formula cell's value, which + // copies a sheet that holds formulas whatever the rewrite does. + s.execute("cell.set", json!({"cell": "Third!A1", "input": "5"})).unwrap(); + let before = s.doc().unwrap().wb.clone(); + s.execute("sheet.rename", json!({"sheet": "Sheet1", "name": "Data"})).unwrap(); + let wb = &s.doc().unwrap().wb; + let shared = |name: &str| std::sync::Arc::ptr_eq(&wb.sheets[wb.sheet_index(name).unwrap()], &before.sheets[before.sheet_index(name).unwrap()]); + assert!(shared("Third"), "Third doesn't name Sheet1"); + assert!(!shared("Other"), "Other's formula names Sheet1"); +} + +/// Every edit that moves references moves those in conditional formats and validation too: +/// inserting rows, renaming a name, deleting a sheet; and deleting a sheet leaves arrays be. +#[test] +fn reference_edits_reach_conditional_formats_and_validation() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Lists"})).unwrap(); + s.execute("range.setValues", json!({"range": "Lists!A1:A3", "values": [["a"], ["b"], ["c"]]})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).ok(); + let sheet1 = s.doc().unwrap().wb.sheet_index("Sheet1").unwrap(); + s.execute("sheet.activate", json!({"sheet": sheet1})).ok(); + s.execute("formulas.defineName", json!({"name": "Opts", "refersTo": "=Lists!$A$1:$A$3"})).unwrap(); + s.execute("data.validation", json!({"range": "Sheet1!B1:B5", "type": "list", "formula1": "=Opts"})).unwrap(); + s.execute("data.validation", json!({"range": "Sheet1!E1:E5", "type": "list", "formula1": "=Lists!$A$1:$A$3"})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "Sheet1!C1:C5", "rule": {"type": "expression", "formula": "=C1>$D$3"}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("cell.set", json!({"cell": "Sheet1!G2", "input": "=B2:B3*2", "array": true})).unwrap(); + let sh = |s: &Session| s.doc().unwrap().wb.sheet(s.doc().unwrap().wb.sheet_index("Sheet1").unwrap()).cloned().unwrap(); + // Inserting a row above moves the rule's references with its range. + s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap(); + let rule = match &sh(&s).cond_formats[0].rule { + gridcraft_model::CfRule::Expression { formula, .. } => formula.clone(), + _ => String::new(), + }; + assert_eq!(rule.trim_start_matches('='), "C2>$D$4"); + // Renaming a name renames it in validation lists. + s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Opts", "refersTo": "=Lists!$A$1:$A$3"})).unwrap(); + assert!(sh(&s).validations.iter().any(|v| v.f1.trim_start_matches('=') == "Choices")); + // Deleting the sheet a list comes from makes it #REF!, and keeps the array formula. + let array_before = sh(&s).cells.iter().find_map(|(_, c)| c.formula.as_ref().and_then(|f| f.array)); + assert!(array_before.is_some()); + let lists = s.doc().unwrap().wb.sheet_index("Lists").unwrap(); + s.execute("home.deleteSheet", json!({"sheet": lists})).unwrap(); + assert!(sh(&s).validations.iter().any(|v| v.f1.contains("#REF!")), "{:?}", sh(&s).validations.iter().map(|v| v.f1.clone()).collect::>()); + assert_eq!(sh(&s).cells.iter().find_map(|(_, c)| c.formula.as_ref().and_then(|f| f.array)), array_before); +} + +/// A copied sheet's chart plots the copy's data. +#[test] +fn a_copied_sheets_chart_plots_the_copy() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["x", "y"], ["a", 1], ["b", 2]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "type": "column"})).unwrap(); + // A series name written as a formula on no sheet keeps its `=`, and stays a reference. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts[0].series[0].name = Some("=A1".into()); + s.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &s.doc().unwrap().wb; + let copy = wb.sheets.iter().find(|sh| sh.name != "Sheet1").unwrap(); + assert!(copy.charts[0].series[0].values.contains(©.name), "{}", copy.charts[0].series[0].values); + assert_eq!(copy.charts[0].series[0].name.as_deref(), Some("=A1")); +} + +/// A rule's formulas follow its ranges: deleting its top-left row re-hosts them at the cell +/// that takes its place, and a cut takes rules with their cells, moving their references once. +#[test] +fn rule_formulas_follow_their_ranges() { + let rule_text = |s: &Session| -> (Vec, Vec) { + let sh = s.doc().unwrap().wb.sheets[0].clone(); + let cf = sh.cond_formats.iter().map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => { + format!("{}@{}", formula.trim_start_matches('='), c.ranges.iter().map(|r| r.a1()).collect::>().join(",")) + } + _ => String::new(), + }); + let dv = sh + .validations + .iter() + .map(|v| format!("{}@{}", v.f1.trim_start_matches('='), v.ranges.iter().map(|r| r.a1()).collect::>().join(","))); + (cf.collect(), dv.collect()) + }; + let mut s = s(); + s.execute("home.conditionalFormat", json!({"range": "A2:A5", "rule": {"type": "expression", "formula": "=B2>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("data.validation", json!({"range": "C2:C5", "type": "custom", "formula1": "=D2>0"})).unwrap(); + s.execute("home.deleteRows", json!({"rows": "2:2"})).unwrap(); + assert_eq!(rule_text(&s), (vec!["B2>0@A2:A4".to_string()], vec!["D2>0@C2:C4".to_string()])); + // Cut A2:A4 to F2: the rule goes with the cells, still testing the cells beside them. + s.execute("edit.cut", json!({"range": "A2:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert_eq!(rule_text(&s).0, vec!["B2>0@F2:F4".to_string()]); + // An overlapping cut moves a self-referring rule's reference once. + let mut s = super::tests::s(); + s.execute("data.validation", json!({"range": "A1:A2", "type": "custom", "formula1": "=A1>0"})).unwrap(); + s.execute("edit.cut", json!({"range": "A1:A2"})).unwrap(); + s.execute("edit.paste", json!({"at": "A2"})).unwrap(); + assert_eq!(rule_text(&s).1, vec!["A2>0@A2:A3".to_string()]); +} + +/// Renaming a table renames every reference to it (a PivotTable's source, a name, a rule) and +/// leaves formulas that don't name it, legacy arrays included, as they are. +#[test] +fn table_rename_renames_every_reference() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["k", "v"], ["a", 1], ["b", 2]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:B3"})).unwrap(); + let table = s.doc().unwrap().wb.sheets[0].tables[0].name.clone(); + s.execute("cell.set", json!({"cell": "D1", "input": "=A2:A3", "array": true})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Tot", "refersTo": format!("=SUM({table}[v])")})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "F1:F3", "rule": {"type": "expression", "formula": format!("=COUNT({table}[v])>0")}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("insert.pivotTable", json!({"source": table, "destination": "Sheet1!H3", "rows": ["k"], "values": ["v"]})).unwrap(); + let array = s.doc().unwrap().wb.sheets[0].cell(CellRef::new(0, 3)).and_then(|c| c.formula.clone()).unwrap(); + s.execute("table.rename", json!({"table": table, "name": "Data"})).unwrap(); + let wb = &s.doc().unwrap().wb; + let sh = &wb.sheets[0]; + assert_eq!( + sh.cell(CellRef::new(0, 3)).and_then(|c| c.formula.clone()).map(|f| (f.text.clone(), f.array, f.dynamic)), + Some((array.text.clone(), array.array, array.dynamic)) + ); + assert_eq!(wb.names.iter().find(|n| n.name == "Tot").map(|n| n.formula.clone()).as_deref(), Some("SUM(Data[v])")); + assert!(matches!(&sh.cond_formats[0].rule, gridcraft_model::CfRule::Expression { formula, .. } if formula.contains("Data[v]"))); + assert_eq!(sh.pivots[0].source, "Data"); + s.execute("data.refreshAll", json!({})).unwrap(); +} + +/// Rules moved whole keep their formulas; a range an edit leaves in place keeps them too; +/// thresholds are read as written; a cut to another sheet names the source sheet's cells. +#[test] +fn rules_moved_whole_or_left_in_place_keep_their_formulas() { + let cf = |s: &Session, sheet: usize| -> Vec { + s.doc().unwrap().wb.sheets[sheet] + .cond_formats + .iter() + .map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => { + format!("{}@{}", formula.trim_start_matches('='), c.ranges.iter().map(|r| r.a1()).collect::>().join(",")) + } + gridcraft_model::CfRule::DataBar { min: gridcraft_model::CfValueKind::Formula(f), .. } => format!("bar {f}"), + _ => String::new(), + }) + .collect() + }; + let rule = |s: &mut Session, range: &str, f: &str| { + s.execute("home.clearRules", json!({"whole": true})).ok(); + s.execute("home.conditionalFormat", json!({"range": range, "rule": {"type": "expression", "formula": f}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + }; + let mut s = s(); + rule(&mut s, "B1:B5", "=C1>0"); + s.execute("sheet.moveColumns", json!({"cols": "B:B", "before": 4})).unwrap(); + // The column moved whole: the rule tests the column that was beside it (C, now B), as a + // formula there would. + assert_eq!(cf(&s, 0), vec!["B1>0@D1:D5".to_string()]); + let mut s = super::tests::s(); + rule(&mut s, "A1:C1", "=B1>0"); + s.execute("home.deleteCells", json!({"range": "A1", "shift": "up"})).unwrap(); + assert_eq!(cf(&s, 0), vec!["B1>0@A1:C1".to_string()]); + // A data bar's threshold formula is read as written: deleting the first row only moves it. + let mut s = super::tests::s(); + s.execute("home.conditionalFormat", json!({"range": "A1:A10", "rule": {"type": "dataBar", "min": {"type": "formula", "value": "MIN(C1:C10)"}}})) + .unwrap(); + assert_eq!(cf(&s, 0), vec!["bar MIN(C1:C10)".to_string()]); + s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap(); + assert_eq!(cf(&s, 0), vec!["bar MIN(C1:C9)".to_string()]); + // A cut to another sheet: the rule still reads the source sheet's cells. + let mut s = super::tests::s(); + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + let one = s.doc().unwrap().wb.sheet_index("Sheet1").unwrap(); + let two = s.doc().unwrap().wb.sheet_index("Two").unwrap(); + s.execute("sheet.activate", json!({"sheet": one})).ok(); + s.execute( + "home.conditionalFormat", + json!({"range": "Sheet1!A2:A4", "rule": {"type": "expression", "formula": "=B2>0"}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("edit.cut", json!({"range": "Sheet1!A2:A4"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": two})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert_eq!(cf(&s, two), vec!["Sheet1!B2>0@F2:F4".to_string()]); + // A data bar's threshold goes along too: its cells into the block, the others on Sheet1. + s.execute("sheet.activate", json!({"sheet": one})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "Sheet1!H1:H10", "rule": {"type": "dataBar", "min": {"type": "formula", "value": "MIN(H1:H10,C1:C10)"}}}), + ) + .unwrap(); + s.execute("edit.cut", json!({"range": "Sheet1!H1:H10"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": two})).unwrap(); + s.execute("edit.paste", json!({"at": "K1"})).unwrap(); + assert_eq!(cf(&s, two).last().map(String::as_str), Some("bar MIN(Two!K1:K10,Sheet1!C1:C10)")); +} + +/// A cut moves the rules its cells hold when it is pasted, not those they held when it was cut. +#[test] +fn a_cut_moves_the_rules_its_cells_hold_at_paste() { + let mut s = s(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("edit.cut", json!({"range": "A1:A3"})).unwrap(); + s.execute("home.clearRules", json!({"whole": true})).unwrap(); + s.execute("data.validation", json!({"range": "A1:A3", "type": "custom", "formula1": "=A1>0"})).unwrap(); + s.execute("edit.paste", json!({"at": "D1"})).unwrap(); + let sh = &s.doc().unwrap().wb.sheets[0]; + assert!(sh.cond_formats.is_empty(), "a cleared rule came back: {:?}", sh.cond_formats); + let dv: Vec = sh.validations.iter().flat_map(|v| v.ranges.iter().map(|r| r.a1())).collect(); + assert_eq!(dv, vec!["D1:D3".to_string()]); +} + +/// A cut whose sheet is renamed before the paste still moves its rules and the references to +/// its cells: the move is made on the sheet as it is now named, not as the clipboard saw it. +#[test] +fn a_cut_pasted_after_its_sheet_is_renamed_moves_its_rules() { + let mut s = s(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("data.validation", json!({"range": "A1:A3", "type": "custom", "formula1": "=A1>0"})).unwrap(); + s.execute("cell.set", json!({"cell": "B5", "input": "=A1"})).unwrap(); + s.execute("edit.cut", json!({"range": "A1:A3"})).unwrap(); + s.execute("sheet.rename", json!({"name": "Data"})).unwrap(); + s.execute("edit.paste", json!({"at": "D1"})).unwrap(); + let sh = &s.doc().unwrap().wb.sheets[0]; + let cf: Vec = sh + .cond_formats + .iter() + .map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => format!("{}@{}", formula.trim_start_matches('='), c.ranges[0].a1()), + _ => String::new(), + }) + .collect(); + assert_eq!(cf, vec!["D1>0@D1:D3".to_string()]); + let dv: Vec = sh.validations.iter().map(|v| format!("{}@{}", v.f1.trim_start_matches('='), v.ranges[0].a1())).collect(); + assert_eq!(dv, vec!["D1>0@D1:D3".to_string()]); + assert_eq!(s.execute("cell.get", json!({"cell": "B5"})).unwrap()["formula"], "=D1"); +} + +/// Moving a column out of a wider rule takes its part of the rule with it, as a cut does: every +/// cell, moved or not, still checks itself. +#[test] +fn moving_a_column_out_of_a_rule_keeps_every_cell_checking_itself() { + let mut s = s(); + s.execute("data.validation", json!({"range": "A1:C3", "type": "custom", "formula1": "=A1>0"})).unwrap(); + s.execute("sheet.moveColumns", json!({"cols": "A:A", "before": 4})).unwrap(); + let ok = |s: &Session, at: &str, input: &str| { + crate::cmd::data::check_validation(&s.doc().unwrap().wb, 0, gridcraft_core::CellRef::parse(at).unwrap(), input).is_none() + }; + // Old A is now D; old B and C are A and B. + for at in ["A1", "B2", "D3"] { + assert!(ok(&s, at, "5"), "{at} takes 5"); + assert!(!ok(&s, at, "-5"), "{at} refuses -5"); + } + // Moved left, a whole range of the rule becomes its top-left: the parts left behind still + // check themselves. + let mut s = super::tests::s(); + s.execute("data.validation", json!({"range": "B1:B3,D1:D3", "type": "custom", "formula1": "=B1>0"})).unwrap(); + s.execute("sheet.moveColumns", json!({"cols": "D:D", "before": 1})).unwrap(); + for at in ["B1", "C2"] { + assert!(ok(&s, at, "5"), "{at} takes 5"); + assert!(!ok(&s, at, "-5"), "{at} refuses -5"); + } +} + +/// A rule's formulas are written for the top-left of all its ranges: when an edit removes the +/// range holding that cell, the rest re-host from it, not from their own top-left. +#[test] +fn rules_rehost_from_the_top_left_of_all_their_ranges() { + let texts = |s: &Session| -> (Vec, Vec) { + let sh = s.doc().unwrap().wb.sheets[0].clone(); + let at = |ranges: &[gridcraft_core::RangeRef]| ranges.iter().map(|r| r.a1()).collect::>().join(","); + let cf = sh.cond_formats.iter().map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => format!("{}@{}", formula.trim_start_matches('='), at(&c.ranges)), + _ => String::new(), + }); + let dv = sh.validations.iter().map(|v| format!("{}@{}", v.f1.trim_start_matches('='), at(&v.ranges))); + (cf.collect(), dv.collect()) + }; + let setup = || { + let mut s = super::tests::s(); + s.execute( + "home.conditionalFormat", + json!({"range": "A1:A5,C10:C12", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}}), + ) + .unwrap(); + s.execute("data.validation", json!({"range": "A1:A5,E10:E12", "type": "custom", "formula1": "=A1>0"})).unwrap(); + s + }; + // Deleting the rows of the first area: the second keeps testing itself. + let mut s = setup(); + s.execute("home.deleteRows", json!({"rows": "1:5"})).unwrap(); + assert_eq!(texts(&s), (vec!["C5>0@C5:C7".to_string()], vec!["E5>0@E5:E7".to_string()])); + // Deleting the cells of the first area, shifting up or left: the second area stays put. + for shift in ["up", "left"] { + let mut s = setup(); + s.execute("home.deleteCells", json!({"range": "A1:A5", "shift": shift})).unwrap(); + assert_eq!(texts(&s), (vec!["C10>0@C10:C12".to_string()], vec!["E10>0@E10:E12".to_string()]), "shift {shift}"); + } +} + +/// A cut is pasted as it is: a transposed, tiled or skip-blanks paste of it is refused and +/// changes nothing, so its rules never land on a block of another shape than its cells, nor +/// replace a destination rule under a cell the paste leaves alone. +#[test] +fn a_cut_is_not_transposed_or_tiled() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:C1", "values": [[1, 2, 3]]})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "A1:C1", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("edit.cut", json!({"range": "A1:C1"})).unwrap(); + assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E1"})).is_err()); + assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "skipBlanks": true, "at": "E1"})).is_err()); + s.execute("selection.set", json!({"range": "E1:G2"})).unwrap(); + assert!(s.execute("edit.pasteSpecial", json!({"what": "all"})).is_err()); + let sh = s.doc().unwrap().wb.sheets[0].clone(); + assert_eq!(sh.value(CellRef::new(0, 0)), Value::Number(1.0)); + assert_eq!(sh.cond_formats[0].ranges.iter().map(|r| r.a1()).collect::>(), vec!["A1:C1".to_string()]); + // Pasted as it is, the rule goes with the cells. + s.execute("edit.paste", json!({"at": "E1"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].cond_formats[0].ranges.iter().map(|r| r.a1()).collect::>(), vec!["E1:G1".to_string()]); +} + +/// Deleting cells in only the first column of a rule's range shifts its top-left cell and keeps the +/// range's size: the rule's formula follows the cell now there, not the deleted one. +#[test] +fn a_rule_follows_its_top_left_through_a_partial_cell_delete() { + let mut s = s(); + s.execute("home.conditionalFormat", json!({"range": "A1:C3", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("data.validation", json!({"range": "A1:C3", "type": "custom", "formula1": "=A1<>B1"})).unwrap(); + s.execute("home.deleteCells", json!({"range": "A1", "shift": "up"})).unwrap(); + let sh = s.doc().unwrap().wb.sheets[0].clone(); + let rule = match &sh.cond_formats[0].rule { + gridcraft_model::CfRule::Expression { formula, .. } => formula.trim_start_matches('=').to_string(), + other => panic!("{other:?}"), + }; + assert_eq!(rule, "A1>0"); + // The cell now at A1 came from A2, which compared itself with B2 (column B didn't move). + assert_eq!(sh.validations[0].f1.trim_start_matches('='), "A1<>B2"); +} + +/// A column moved out of a rule's range takes its part of the rule reading what the column read: +/// a rule on B1:D1 testing the cell to its left, with D moved before B, still tests old C (now D) +/// at the moved cell, and a rule on the moved column alone still tests that column. +#[test] +fn a_moved_column_keeps_what_its_part_of_a_rule_reads() { + let mut s = s(); + s.execute("home.conditionalFormat", json!({"range": "B1:D1", "rule": {"type": "expression", "formula": "=A1>0"}, "style": {"fill": "#FFC7CE"}})) + .unwrap(); + s.execute("data.validation", json!({"range": "D2", "type": "custom", "formula1": "=D2>0"})).unwrap(); + s.execute("sheet.moveColumns", json!({"cols": "D:D", "before": 1})).unwrap(); + let sh = s.doc().unwrap().wb.sheets[0].clone(); + let mut rules: Vec = sh + .cond_formats + .iter() + .map(|c| match &c.rule { + gridcraft_model::CfRule::Expression { formula, .. } => { + format!("{}@{}", formula.trim_start_matches('='), c.ranges.iter().map(|r| r.a1()).collect::>().join(",")) + } + other => format!("{other:?}"), + }) + .collect(); + rules.sort(); + assert_eq!(rules, vec!["A1>0@C1:D1".to_string(), "D1>0@B1".to_string()]); + assert_eq!(sh.validations[0].f1.trim_start_matches('='), "B2>0"); +} + +/// Internal hyperlinks keep the place they name as typed, as Excel's "Place in This Document" +/// links do: renaming or deleting a sheet, or inserting rows, leaves them as they were. +#[test] +fn internal_link_targets_stay_as_typed() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Lists"})).unwrap(); + let one = s.doc().unwrap().wb.sheet_index("Sheet1").unwrap(); + s.execute("insert.link", json!({"cell": "Sheet1!A1", "target": "Lists!B5"})).unwrap(); + s.execute("insert.link", json!({"cell": "Sheet1!A2", "target": "Sheet1!C9"})).unwrap(); + s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap(); + let lists = s.doc().unwrap().wb.sheet_index("Lists").unwrap(); + s.execute("sheet.rename", json!({"sheet": lists, "name": "Data"})).unwrap(); + s.execute("home.deleteSheet", json!({"sheet": lists})).unwrap(); + let wb = &s.doc().unwrap().wb; + let one = wb.sheet_index("Sheet1").unwrap_or(one); + let mut targets: Vec = wb.sheets[one].hyperlinks.values().map(|h| h.target.clone()).collect(); + targets.sort(); + assert_eq!(targets, vec!["Lists!B5".to_string(), "Sheet1!C9".to_string()]); +} + #[test] fn circle_invalid_says_when_its_scan_allowance_ended_early() { let mut s = s(); diff --git a/crates/engine/src/tests/objects.rs b/crates/engine/src/tests/objects.rs index d78cd406fd..6d30dd79b9 100644 --- a/crates/engine/src/tests/objects.rs +++ b/crates/engine/src/tests/objects.rs @@ -252,6 +252,53 @@ fn chart_series_follow_cut_moves_renames_and_sheet_deletes() { assert_eq!(values(&s), "Inputs!$A$1:$A$3"); } +/// A series name that is a bare word is a label, as a chart reads it: renaming a table of that +/// name leaves it be, while a series named by a defined name follows the name's rename. +#[test] +fn chart_series_names_follow_names_but_not_labels() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["v"], [5], [2]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:A3", "name": "Sales"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Title", "refersTo": "=Sheet1!$A$1"})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A2:A3", "type": "column"})).unwrap(), "chart"); + let set = |s: &mut Session, label: &str, named: &str| { + let ch = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap(); + ch.series.truncate(1); + let mut second = ch.series[0].clone(); + ch.series[0].name = Some(label.into()); + second.name = Some(named.into()); + ch.series.push(second); + }; + let names = |s: &Session| -> Vec { + sheet(s, 0).charts.iter().find(|c| c.id == chart).map(|c| c.series.iter().filter_map(|se| se.name.clone()).collect()).unwrap_or_default() + }; + // A name another sheet holds isn't one this chart sees. + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Sales", "refersTo": "=Two!$A$1", "scope": "Two"})).unwrap(); + set(&mut s, "Sales", "Title"); + s.execute("table.rename", json!({"table": "Sales", "name": "Revenue"})).unwrap(); + assert_eq!(names(&s), ["Sales", "Title"], "a label isn't the table"); + s.execute("formulas.defineName", json!({"name": "Heading", "refersTo": "=Sheet1!$A$1", "oldName": "Title"})).unwrap(); + assert_eq!(names(&s), ["Sales", "Heading"], "a defined name follows its rename"); + // A label shaped like a cell is a label too. + set(&mut s, "Q1", "Sheet1!$A$1"); + s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap(); + assert_eq!(names(&s), ["Q1", "Sheet1!$A$2"]); +} + +/// A sheet may be named `#REF!`: a chart's source on it is not taken for one that's gone. +#[test] +fn a_chart_source_on_a_sheet_named_ref_error_is_kept() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[3], [5]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:A2", "type": "column"})).unwrap(); + s.execute("sheet.rename", json!({"sheet": 0, "name": "#REF!"})).unwrap(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.rename", json!({"sheet": "Other", "name": "Else"})).unwrap(); + let source = sheet(&s, s.doc().unwrap().wb.sheet_index("#REF!").unwrap()).charts[0].source.clone(); + assert_eq!(source.as_deref(), Some("'#REF!'!A1:A2")); +} + #[test] fn a_copied_sheet_gives_its_objects_fresh_ids() { let mut s = s(); diff --git a/crates/engine/src/tests/python_cells.rs b/crates/engine/src/tests/python_cells.rs index 9bc8b4999d..1dea97faf3 100644 --- a/crates/engine/src/tests/python_cells.rs +++ b/crates/engine/src/tests/python_cells.rs @@ -531,6 +531,21 @@ fn python_code_with_an_empty_value_counts_as_content() { assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array"))); } +/// Renaming a defined name or a table renames it in Python cells' `xl()` references too. +#[test] +fn xl_references_follow_name_and_table_renames() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["k", "v"], ["a", 1], ["b", 2]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:B3"})).unwrap(); + let table = s.doc().unwrap().wb.sheets[0].tables[0].name.clone(); + s.execute("formulas.defineName", json!({"name": "Opts", "refersTo": "=Sheet1!$A$2:$A$3"})).unwrap(); + plant(&mut s, 0, "E1", &format!("a = xl(\"Opts\")\nb = xl(\"{table}[v]\")")); + s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Opts", "refersTo": "=Sheet1!$A$2:$A$3"})).unwrap(); + assert_eq!(code(&s, 0, "E1").as_deref(), Some(format!("a = xl(\"Choices\")\nb = xl(\"{table}[v]\")").as_str())); + s.execute("table.rename", json!({"table": table, "name": "Data"})).unwrap(); + assert_eq!(code(&s, 0, "E1").as_deref(), Some("a = xl(\"Choices\")\nb = xl(\"Data[v]\")")); +} + #[test] fn inserting_a_link_without_text_preserves_an_empty_python_cell() { let mut s = s(); diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index ba6616d64c..60e344ffb3 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -293,8 +293,9 @@ pub fn rename_sheet(e: Expr, old: &str, new: &str) -> Expr { } // Sheet-qualified defined name `Old!MyName` is stored as one string, with the bare sheet name as the parser // stores it (the printer adds the quotes). - Expr::Name(n) => match n.split_at_checked(old.len()) { - Some((head, rest)) if head.eq_ignore_ascii_case(old) && rest.starts_with('!') => Expr::Name(format!("{new}{rest}")), + // A sheet name may itself hold a '!', so the name splits at its last one. + Expr::Name(n) => match n.rsplit_once('!') { + Some((sheet, rest)) if sheet.eq_ignore_ascii_case(old) => Expr::Name(format!("{new}!{rest}")), _ => Expr::Name(n), }, other => other, diff --git a/crates/formula/src/tests.rs b/crates/formula/src/tests.rs index 274a66667f..1b4789a955 100644 --- a/crates/formula/src/tests.rs +++ b/crates/formula/src/tests.rs @@ -238,6 +238,10 @@ fn rename_sheet_updates_qualified_names() -> Result<(), Box Vec<&mut String> { + match self { + CfRule::CellIs { a, b, .. } => std::iter::once(a).chain(b.as_mut()).collect(), + CfRule::Expression { formula, .. } => vec![formula], + _ => Vec::new(), + } + } + + /// [`CfRule::formulas_mut`], read only. + pub fn formulas(&self) -> Vec<&String> { + let kinds: Vec<&CfValueKind> = match self { + CfRule::CellIs { a, b, .. } => return std::iter::once(a).chain(b.as_ref()).collect(), + CfRule::Expression { formula, .. } => return vec![formula], + CfRule::ColorScale { stops } => stops.iter().map(|(k, _)| k).collect(), + CfRule::DataBar { min, max, .. } => vec![min, max], + CfRule::IconSet { thresholds, .. } => thresholds.iter().collect(), + _ => Vec::new(), + }; + kinds + .into_iter() + .filter_map(|k| match k { + CfValueKind::Formula(t) => Some(t), + _ => None, + }) + .collect() + } + + /// All the rule's formulas, thresholds included: what an edit that moves references + /// rewrites. + pub fn formulas_mut(&mut self) -> Vec<&mut String> { + let kinds: Vec<&mut CfValueKind> = match self { + CfRule::CellIs { a, b, .. } => return std::iter::once(a).chain(b.as_mut()).collect(), + CfRule::Expression { formula, .. } => return vec![formula], + CfRule::ColorScale { stops } => stops.iter_mut().map(|(k, _)| k).collect(), + CfRule::DataBar { min, max, .. } => vec![min, max], + CfRule::IconSet { thresholds, .. } => thresholds.iter_mut().collect(), + _ => Vec::new(), + }; + kinds + .into_iter() + .filter_map(|k| match k { + CfValueKind::Formula(t) => Some(t), + _ => None, + }) + .collect() + } + /// The differential style a matching rule applies; colour scales, data bars and icon sets have none. pub fn style(&self) -> Option<&Style> { match self { @@ -257,6 +307,18 @@ impl CfRule { } } +impl Validation { + /// The validation's formulas (for its range's top-left cell). + pub fn formulas_mut(&mut self) -> Vec<&mut String> { + std::iter::once(&mut self.f1).chain(self.f2.as_mut()).collect() + } + + /// [`Validation::formulas_mut`], read only. + pub fn formulas(&self) -> Vec<&String> { + std::iter::once(&self.f1).chain(self.f2.as_ref()).collect() + } +} + /// Number of icons in an icon set (`3Arrows` → 3, `5Quarters` → 5), always 3 to 5. pub fn icon_count(set: &str) -> usize { set.chars().next().and_then(|c| c.to_digit(10)).unwrap_or(3).clamp(3, 5) as usize diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index b1f875b3c1..9522e4e3dc 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -31,7 +31,7 @@ pub use style::{ }; pub use workbook::{ CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString, - ShowObjects, Workbook, WorkbookView, + RefHost, ShowObjects, Workbook, WorkbookView, }; /// Font used for new workbooks. Only a name: renderers substitute an available open font diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index ab401828da..4402b368b6 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -343,7 +343,209 @@ impl std::fmt::Debug for ActiveSheet { } } +/// Where a reference is held, for [`Workbook::rewrite_references`]. +#[derive(Clone, Copy, Debug)] +pub struct RefHost<'a> { + /// The sheet holding it, or a defined name's scope (`None`: the workbook). + pub sheet: Option, + /// The name unqualified references in it are on: its sheet's (a sheet-level defined name's + /// scope sheet, where they are read), or [`NAME_HOST`] for a workbook-level defined name + /// (read on whichever sheet uses it). + pub name: &'a str, +} + +/// [`RefHost::name`] for a workbook-level defined name: `[` and `]` can't be in a sheet's name, so +/// no sheet's references are taken for a name's. +pub const NAME_HOST: &str = "[]"; + +/// Formula text with `f` applied to its references; text that isn't a formula, or that `f` +/// doesn't change, stays as it is (a leading `=` is kept). Whether it changed. +fn rewrite_with(t: &mut String, f: &dyn Fn(Expr) -> Expr, parse: fn(&str) -> Result) -> bool { + let body = t.trim_start_matches('='); + let Ok(e) = parse(body) else { return false }; + let before = gridcraft_formula::print(&e); + let after = gridcraft_formula::print(&f(e)); + if after == before { + return false; + } + *t = if t.starts_with('=') { format!("={after}") } else { after }; + true +} + +fn rewrite_text(t: &mut String, f: &dyn Fn(Expr) -> Expr) -> bool { + rewrite_with(t, f, gridcraft_formula::parse) +} + impl Workbook { + /// Rewrites every reference the workbook holds with `f`, given where each is held, in one + /// place: cell formulas (keeping their array and spill kind), defined names, conditional + /// formats and data validation (written for their range's top-left cell, so they move as + /// a cell formula there does), chart series (a chart's source block + /// the edit breaks is dropped; one already broken is kept), sparklines, PivotTable sources + /// (not one that is a table's name alone, which reads the table first) and form controls' + /// linked cells. The engine's reference-moving edits (renaming sheets and names, deleting sheets, + /// renaming tables, inserting and deleting lines and cells, cut-moves) go through it. Not + /// visited: table calculated-column and totals formulas, a PivotChart's link to its + /// PivotTable, a slicer's table, and Python cells' `xl()` references (the engine rewrites + /// the last itself, and a PivotChart's link on a sheet rename). A legacy array's own range is the + /// caller's to move. Internal + /// hyperlinks keep the place they name as typed, as Excel's do. A sheet nothing changes on + /// stays shared. + pub fn rewrite_references(&mut self, f: &dyn Fn(RefHost<'_>, Expr) -> Expr) { + let sheet_names: Vec = self.sheets.iter().map(|s| s.name.clone()).collect(); + for n in &mut self.names { + let name = n.scope.and_then(|i| sheet_names.get(i)).map_or(NAME_HOST, String::as_str); + let host = RefHost { sheet: n.scope, name }; + rewrite_with(&mut n.formula, &|e| f(host, e), gridcraft_formula::parse_name); + } + // A series name is read by the chart as a reference when it starts with `=`, names a + // sheet (`!`) or is a defined name its sheet sees; anything else (a word, a table's + // name, `Q1`) is a label and is left as written. + let names: Vec<(String, Option)> = self.names.iter().map(|n| (n.name.to_lowercase(), n.scope)).collect(); + // A PivotTable source that is a table's name alone reads the table before any defined + // name of that name (`pivot::resolve_source`), so a name's edit doesn't reach it. + let tables: Vec = self.sheets.iter().flat_map(|s| s.tables.iter().map(|t| t.name.to_lowercase())).collect(); + let table_source = |t: &str| tables.contains(&t.trim().trim_start_matches('=').trim().to_lowercase()); + let label = |t: &str, si: usize| { + let t = t.trim(); + let defined = || names.iter().any(|(n, scope)| scope.is_none_or(|s| s == si) && *n == t.to_lowercase()); + !t.starts_with('=') && !t.contains('!') && !defined() + }; + for (si, shared) in self.sheets.iter_mut().enumerate() { + // Worked out on the shared sheet; a list is copied only when something in it + // changes, and a sheet nothing changes on stays shared with undo snapshots. + let sh: &Sheet = shared; + let host = RefHost { sheet: Some(si), name: &sh.name }; + let f = |e: Expr| f(host, e); + let changes = |t: &str| rewrite_with(&mut t.to_string(), &f, gridcraft_formula::parse); + let cells: Vec<(gridcraft_core::CellRef, Formula)> = sh + .cells + .iter() + .filter_map(|(c, cell)| { + // Trees are compared, not printed text: a formula the edit leaves alone keeps + // its stored text, even text that isn't canonical, and isn't printed. + let old = cell.formula.as_ref()?; + let new = old.with_expr(|e| Some(f(e.clone())).filter(|n| n != e))??; + Some((c, Formula { array: old.array, dynamic: old.dynamic, ..Formula::from_expr(new) })) + }) + .collect(); + let cond_formats = sh.cond_formats.iter().any(|cf| cf.rule.formulas().into_iter().any(|t| changes(t))).then(|| { + let mut v = sh.cond_formats.clone(); + v.iter_mut().flat_map(|cf| cf.rule.formulas_mut()).for_each(|t| { + rewrite_text(t, &f); + }); + v + }); + let validations = sh.validations.iter().any(|dv| dv.formulas().into_iter().any(|t| changes(t))).then(|| { + let mut v = sh.validations.clone(); + v.iter_mut().flat_map(|dv| dv.formulas_mut()).for_each(|t| { + rewrite_text(t, &f); + }); + v + }); + // A chart's source block that no longer exists is dropped. + // (Read from the tree: a sheet may be named `#REF!`.) + let dead = |src: Option<&str>| { + src.and_then(|s| gridcraft_formula::parse(s.trim_start_matches('=')).ok()).is_some_and(|e| { + let mut hit = false; + e.walk(&mut |x| hit |= matches!(x, Expr::Error(gridcraft_core::CellError::Ref))); + hit + }) + }; + let charts = sh + .charts + .iter() + .any(|ch| { + ch.source.as_deref().is_some_and(changes) + || ch.series.iter().any(|se| { + changes(&se.values) + || [&se.categories, &se.bubble_sizes].into_iter().flatten().any(|t| changes(t)) + || se.name.as_deref().is_some_and(|t| !label(t, si) && changes(t)) + }) + }) + .then(|| { + let mut v = sh.charts.clone(); + for ch in &mut v { + for se in &mut ch.series { + rewrite_text(&mut se.values, &f); + for t in [&mut se.categories, &mut se.bubble_sizes].into_iter().flatten() { + rewrite_text(t, &f); + } + if let Some(t) = se.name.as_mut().filter(|t| !label(t, si)) { + rewrite_text(t, &f); + } + } + // A source this edit breaks is dropped; one already broken before it + // (from a file, or an earlier edit) is kept as it was. + let was_dead = dead(ch.source.as_deref()); + if let Some(src) = &mut ch.source { + rewrite_text(src, &f); + } + if !was_dead && dead(ch.source.as_deref()) { + ch.source = None; + } + } + v + }); + let sparklines = sh.sparklines.iter().any(|sp| changes(&sp.source)).then(|| { + let mut v = sh.sparklines.clone(); + v.iter_mut().for_each(|sp| { + rewrite_text(&mut sp.source, &f); + }); + v + }); + let pivots = sh.pivots.iter().any(|pt| !table_source(&pt.source) && changes(&pt.source)).then(|| { + let mut v = sh.pivots.clone(); + v.iter_mut().filter(|pt| !table_source(&pt.source)).for_each(|pt| { + rewrite_text(&mut pt.source, &f); + }); + v + }); + // A form control's linked cell. + let controls = sh.controls.iter().any(|c| c.link.as_deref().is_some_and(changes)).then(|| { + let mut v = sh.controls.clone(); + v.iter_mut().flat_map(|c| c.link.as_mut()).for_each(|t| { + rewrite_text(t, &f); + }); + v + }); + if cells.is_empty() + && cond_formats.is_none() + && validations.is_none() + && charts.is_none() + && sparklines.is_none() + && pivots.is_none() + && controls.is_none() + { + continue; + } + let sh = Arc::make_mut(shared); + for (c, formula) in cells { + if let Some(cell) = sh.cells.get_mut(c) { + cell.formula = Some(Arc::new(formula)); + } + } + if let Some(v) = cond_formats { + sh.cond_formats = v; + } + if let Some(v) = validations { + sh.validations = v; + } + if let Some(v) = charts { + sh.charts = v; + } + if let Some(v) = sparklines { + sh.sparklines = v; + } + if let Some(v) = pivots { + sh.pivots = v; + } + if let Some(v) = controls { + sh.controls = v; + } + } + } + /// A new workbook with one sheet, "Sheet1". pub fn new() -> Workbook { Workbook { @@ -600,6 +802,36 @@ mod tests { Ok(()) } + /// A rewrite copies only the sheets it changes: the others stay shared (with undo snapshots). + #[test] + fn rewrite_references_leaves_untouched_sheets_shared() -> Result<(), Box> { + let mut wb = Workbook::new(); + let mut other = Sheet::new("Other"); + other.set_cell(gridcraft_core::CellRef::new(0, 0), crate::Cell::formula(Formula::new("Sheet1!A1+1"))); + wb.sheets.push(Arc::new(other)); + let mut third = Sheet::new("Third"); + third.set_cell(gridcraft_core::CellRef::new(0, 0), crate::Cell::formula(Formula::new("A1+1"))); + // A rule that doesn't name the sheet leaves its sheet shared; one that does is rewritten. + third.validations.push(crate::Validation { f1: "=A1>0".into(), ..Default::default() }); + wb.sheets.push(Arc::new(third)); + let mut fourth = Sheet::new("Fourth"); + fourth.validations.push(crate::Validation { f1: "=Sheet1!A1>0".into(), ..Default::default() }); + wb.sheets.push(Arc::new(fourth)); + let snapshot = wb.clone(); + wb.rewrite_references(&|_, e| gridcraft_formula::adjust::rename_sheet(e, "Sheet1", "Data")); + let shared = |i: usize| -> Result> { + Ok(Arc::ptr_eq(wb.sheets.get(i).ok_or("sheet")?, snapshot.sheets.get(i).ok_or("sheet")?)) + }; + assert!(shared(0)?, "nothing on Sheet1 names it"); + assert!(!shared(1)?, "Other's formula names Sheet1"); + assert!(shared(2)?, "Third's formula and rule are unqualified"); + assert!(!shared(3)?, "Fourth's rule names Sheet1"); + assert_eq!(wb.sheets.get(3).and_then(|s| s.validations.first()).map(|v| v.f1.as_str()), Some("=Data!A1>0")); + let f = wb.sheets.get(1).and_then(|s| s.cell(gridcraft_core::CellRef::new(0, 0))).and_then(|c| c.formula.clone()).ok_or("formula")?; + assert_eq!(f.text, "Data!A1+1"); + Ok(()) + } + #[test] fn sheet_names() { let wb = Workbook::new(); diff --git a/docs/architecture.md b/docs/architecture.md index febe96fcd9..051f15f21f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md). @@ -203,6 +203,36 @@ at its sheet again, so it is drawn, pointed from and committed there, and its po message, when its sheet is gone, or when it holds Python code (in Python mode, or begun on a Python cell) that sheet protection now hides, as the Python editor window closes then. +## Reference rewriting + +`Workbook::rewrite_references` is the one walker over the places a workbook holds a reference: +cell formulas (keeping their legacy-array range and spill kind), defined names, conditional +formats, data validation, chart series and source blocks, sparklines, PivotTable sources and form +controls' linked cells. It hands the rewrite a `RefHost` (the holding sheet or a name's scope, and +the sheet name unqualified references are on). A formula whose tree the rewrite leaves alone keeps +its stored text. Not visited: table calculated-column and totals formulas, a PivotChart's link to its PivotTable (a sheet rename moves it itself) and a slicer's table. The engine's +reference-moving edits go through it: renaming and deleting +sheets, renaming defined names and tables, inserting and deleting rows, columns and cells, and +cut-and-paste (`engine::cmd::edit::rewrite_all_formulas`, plus Python `xl()` literals); a legacy +array's own range is moved by the caller. Internal hyperlinks keep the place they name as typed, +as Excel's do. A sheet nothing changes on stays shared with undo snapshots. + +Conditional-format and validation formulas are written for the top-left cell of all the rule's +ranges. When an edit moves that cell (cuts a range short, or removes the range holding it), the +rule's top-left-relative formulas (`CfRule::relative_formulas_mut`, `Validation::formulas_mut`) +are first re-hosted at the cell that takes its place (`rehost_rule`, given the ranges as they were +before the edit), then moved once by the walker, so deleting a rule's first row leaves its formulas reading +the same cells. A range moved whole or left in place keeps its formulas, and colour-scale, data-bar +and icon-set thresholds are read as written. A rule keeps one formula for all its cells, so when an +edit shifts some of a rule's cells and not others (lines inserted or deleted inside its range, Move +Columns across it), a relative reference read at cells on the far side of the shift lands where the +top-left cell's reference puts it, not on the data that cell read before; rules whose cells read +themselves, and absolute references, are unaffected. A cut, and Move Columns, take the rules on their +cells with them (`move_cut_rules`, on the engine's `Rule` trait, `remove_rule_cells` and +`moved_rule_parts`), so their ranges and formulas move together, once; a cut to another sheet qualifies their references with the source sheet. A cut is +pasted as it is: Paste Special refuses to transpose it, tile it over a larger selection or skip its +blanks, as Excel offers none of those for a cut. + ## Equations An equation is a shape (`ShapeKind::Equation`) whose `text` is its LaTeX source; it selects, @@ -242,6 +272,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Reference rewriting: `Workbook::rewrite_references` as the one walker for every reference-moving edit; rule formulas re-hosted by how their ranges moved and moved with a cut | | 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` | | 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | From f9af787c7b011440402433d48487993650aa2eca Mon Sep 17 00:00:00 2001 From: kbarni Date: Tue, 24 Nov 2026 00:32:01 +0100 Subject: [PATCH 08/10] Dropdown filter (#2119) * Searchable validation dropdown lists * double dropdown bug solved * performance improvements for dropdown list filtering * docstrings and documentation added * precisions regarding accented characters for dropdown list search * Latin extended characters added to accent list in dropdown list search * formula bar check button handled as enter for highlighted entry * capping list at 10,000 entries * Bound the searched validation list's source work A searched list (data.validationList, and the edit that typing into a list cell opens) read its whole source first: a whole-column list evaluated every cell into an array and folded each entry, so a search with few or no matches could still stall the UI. The search now reads at most LIST_SOURCE_BUDGET (200,000) cells of the source: a range is walked cell by cell instead of evaluated, a computed source gets the budget as its formula work, and `truncated` reports when the source was cut short. The popup says when entries aren't shown. The validation membership check still reads the whole list. * Bound the dropdown arrow's validation list The full list that the dropdown arrow or Alt+Down opens called list_items every frame while it was open and drew a button for every entry, so a list over a huge column reread its source and laid out all of it on each repaint. It now reads the list once with list_search_source (within LIST_SOURCE_BUDGET), keeps it while the popup stays open on the same cell of the same workbook version, and draws only the rows in view, saying when entries aren't shown. Rows are measured at their real button height, so the popup shows the eight rows it was meant to (it showed six). * Dropdown list fixes 1. Row height: the search popup now measures its rows at the real button height, through a helper shared with the arrow picker. It shows eight rows, the highlight stays in view and the end of a long list is reachable. 2. Duplicate call: the second e.update_list() in control.rs is gone. 3. Stale cache: list_picker_items is cleared wherever list_picker is cleared for an edit (start_edit and the editor branch of list_picker). 4. Translation: "More entries not shown" is one constant and goes through lang.tr(...) in both popups. I did not add catalog entries, so it still shows in English in every language until translations are written. 5. Flip above: the search popup opens above the cell when it would run past the bottom of the window, using the same rule as the arrow picker. 6. Width: the popup width is measured once per search and cached in ListSearch::text_width; update_list resets it. * Validation lists: fixed-height rows, translated cut-short note The rows of both validation list popups are drawn in slots of exactly the height the popup scrolls by. A button sizes itself to its laid-out text, which can be a pixel taller than the font's nominal line height, so the last visible row ran under the "More entries not shown" note with the pinned test fonts (the CI gate failure). The note is translated in all 18 interface catalogs, with a test that no catalog falls back to English. The validation-list UI tests move into the shared integration binary and use the pinned font harness, so they no longer depend on host fonts. * Validation list note: use each catalog's word for list items --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: skylartaylor --- ROADMAP.md | 4 +- crates/calc/src/eval.rs | 11 + crates/calc/src/lib.rs | 2 +- crates/calc/src/recalc.rs | 32 ++ crates/engine/src/cmd/data.rs | 16 +- crates/engine/src/cmd/data/tests.rs | 141 +++++++ crates/engine/src/cmd/data/validation.rs | 220 +++++++++++ crates/ui-egui/src/app/editing.rs | 24 +- crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/editor.rs | 244 ++++++++++++ crates/ui-egui/src/formula_bar.rs | 22 ++ crates/ui-egui/src/grid.rs | 15 +- crates/ui-egui/src/grid/editor.rs | 162 +++++++- crates/ui-egui/src/grid/show.rs | 3 +- crates/ui-egui/src/i18n.rs | 14 + crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/el.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/nl.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt.rs | 1 + crates/ui-egui/src/i18n/ro.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/sr.rs | 1 + crates/ui-egui/src/i18n/tr.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + crates/ui-egui/src/i18n/vi.rs | 1 + crates/ui-egui/src/i18n/zh.rs | 1 + crates/ui-egui/tests/it/main.rs | 1 + .../tests/it/validation_list_search.rs | 367 ++++++++++++++++++ docs/ui-parity.md | 8 +- 36 files changed, 1284 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/tests/it/validation_list_search.rs diff --git a/ROADMAP.md b/ROADMAP.md index 6df4e6c941..aba1817753 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -3,7 +3,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away > **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -172,6 +172,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-22 | On the desktop every workbook window is a native window of its own: New, Open and New Window open one, each keeps its own cell draft, dialog and ribbon, and the macOS menu bar acts on the window focused last. Closing one of several windows on a workbook doesn't ask; closing a workbook's last window, or quitting, asks about unsaved changes in that window. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar. First craft-libs `craft-window` use (window list and viewport driver) | | 2026-10-22 | View › New Window opens a second window on the same workbook (it used to open a copy whose Save overwrote the original): each window has its own selection, active sheet and scroll, titles read "Book1:1" / "Book1:2", and Switch Windows, Hide, Unhide and Close act per window. The control channel, CLI `send` and MCP tools take an optional `window` or `doc` id and default to the active window; `window.list` (MCP `list_windows`) lists the windows | | 2026-10-22 | Typing in a cell and then choosing File › New no longer strands the first workbook: the entry is committed into its own workbook before any File or window command (a refused entry stays open and stops the command), View › Switch Windows and the macOS Window menu list the open workbooks with unsaved markers, `view.switchWindows {doc}` switches by a stable workbook id, and the macOS Quit item asks about unsaved workbooks | +| 2026-10-21 | Data validation lists are searchable: typing into the cell filters the dropdown to entries with a word starting with the typed text (case ignored, and the accents of Latin letters such as é, ç, ß, ł, ș, ǎ and Vietnamese ộ: Latin-1, Latin Extended-A and -B, Latin Extended Additional; other scripts keep their marks), and Enter or Tab takes the highlighted entry; `data.validationList` exposes the same search to the CLI, MCP and agents | | 2026-10-21 | Page Setup paper sizes match Japanese Excel: `B4`/`B5`/`B6` are the JIS sizes (ISO B4/B5/B6 stay reachable by name), so a Japanese B5 worksheet prints at 182×257 mm; Japanese Postcard (100×148 mm), Double Postcard (148×200 mm), Envelope #3/#4 (120×235/90×205 mm), Kaku #2/#3 (240×332/216×277 mm) and A6 are added, both sizes reach the PDF page (`file.exportPdf`/`file.print` MediaBox) and the size survives an XLSX round-trip; the Page Layout Size menu lists them. `B4`/`B5` used to be the ISO sizes, which is changed here | | 2026-10-20 | Japanese interface catalog covers every key the Brazilian Portuguese catalog translates: the 398-label shared core plus 545 dialog, message, Backstage and menu strings (943 total, ~43% of ~2,200). A test parses `pt.rs`'s source, so the two catalogs stay in step | | 2026-10-20 | Interface translated into Dutch (518 labels: ribbon, context menus, File view, dialog titles, Options); `nl`, `nl-NL`, `nl-BE` locale tags resolve to Dutch | @@ -309,6 +310,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-22 | minor | Progress log: a native window per workbook window | | 2026-10-22 | minor | Progress log: New Window shares the workbook; window ids for scripts and MCP | | 2026-10-22 | minor | Progress log: drafts stay in their workbook, Switch Windows, macOS Quit asks to save | +| 2026-10-21 | minor | Progress log: searchable data validation lists | | 2026-10-21 | minor | Page Setup paper sizes: JIS B4/B5/B6 (ISO by name), Japanese postcards and envelopes, A6; PDF page size follows, XLSX round-trips | | 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row | | 2026-10-19 | minor | Progress log: long flat operator chains (#916) | diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 5254404747..d10de1240b 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -265,6 +265,17 @@ impl<'h> Evaluator<'h> { } } + /// Gives this evaluation `work` units instead of [`EVAL_WORK`] (never more than that). + pub fn with_work(mut self, work: u64) -> Self { + self.work = work.min(EVAL_WORK); + self + } + + /// Whether a spend found too little work left (the formula stopped with `#CALC!`). + pub fn is_exhausted(&self) -> bool { + self.exhausted + } + /// Spends `units` of this cell's work; `false` (and nothing left) when there isn't enough. pub(crate) fn spend(&mut self, units: u64) -> bool { match self.work.checked_sub(units) { diff --git a/crates/calc/src/lib.rs b/crates/calc/src/lib.rs index 2f7933d711..794a3f97f1 100644 --- a/crates/calc/src/lib.rs +++ b/crates/calc/src/lib.rs @@ -12,7 +12,7 @@ mod trimrange; pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function}; pub use precision::DisplayedPrecision; -pub use recalc::{Calc, Key, evaluate, now_serial}; +pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial}; #[cfg(test)] mod tests; diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index f38ed8d91c..92ea595f19 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -831,6 +831,38 @@ pub fn evaluate_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> V ev.value(expr) } +/// What [`evaluate_bounded`] found: the formula's reference (not read), its value, or that it ran +/// out of work. +#[derive(Clone, Debug)] +pub enum Bounded { + /// The formula is a reference (`$B$1:$B$9`, a name for one, `OFFSET(…)`): its areas, unread. + Areas(Vec), + Value(Value), + /// The formula needed more than the work it was given. + Exhausted, +} + +/// Evaluates a formula in the context of a cell with at most `work` units of work (one per +/// expression evaluated, per cell read, …), keeping a reference result as its areas so the caller +/// can read as much of them as it needs (a validation list's search source). +pub fn evaluate_bounded(wb: &Workbook, sheet: usize, at: CellRef, formula: &str, work: u64) -> Bounded { + let body = formula.strip_prefix('=').unwrap_or(formula); + let Ok(expr) = gridcraft_formula::parse(body) else { return Bounded::Value(Value::Error(CellError::Name)) }; + let exprs = HashMap::default(); + let mut rng = 0x1234_5678_9ABC_DEF0u64; + let mut host = PassHost::new(wb, &exprs, &mut rng, now_serial()); + let mut ev = Evaluator::new(&mut host, sheet, at).with_work(work); + let r = ev.eval(&expr); + if ev.is_exhausted() { + return Bounded::Exhausted; + } + match r { + crate::eval::Ev::R(areas) => Bounded::Areas(areas), + crate::eval::Ev::V(v) => Bounded::Value(v), + crate::eval::Ev::L(_) => Bounded::Value(Value::Error(CellError::Calc)), + } +} + fn prof_now() -> f64 { gridcraft_core::date::unix_now_ms().unwrap_or(0.0) } diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index e6b90d2512..2c786bf0a8 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -32,8 +32,11 @@ use sort::{quick_sort, sort}; #[cfg(test)] use tools::split_delimited; use tools::{remove_duplicates, text_to_columns}; -pub use validation::{check_validation, list_items}; -use validation::{circle_invalid, validate_cmd, validation}; +pub use validation::{ + LIST_MATCH_CAP, LIST_SOURCE_BUDGET, ListSource, check_validation, filter_list_items, list_items, list_search_source, search_fold, search_matches, + search_term, +}; +use validation::{circle_invalid, validate_cmd, validation, validation_list_cmd}; pub(super) use validation::{move_rule_formula, moved_rule_parts, remove_rule_cells, remove_validation_cells}; pub fn specs() -> Vec { @@ -99,6 +102,15 @@ pub fn specs() -> Vec { validation ), cmd!(query "data.validate", "Check Value Against Validation", [], None, "{cell?, input} → {ok, message?}", has_doc, validate_cmd), + cmd!( + query "data.validationList", + "Validation List Items", + [], + None, + "{cell?, search?} → {items: [..], truncated} (the cell's list validation entries; `search` keeps those with a word starting with it, ignoring case and the accents of Latin letters; at most 10,000 entries, read from at most 200,000 cells of the source; `truncated`: more may exist)", + has_doc, + validation_list_cmd + ), cmd!(noundo "data.circleInvalid", "Circle Invalid Data", ["Data", "Data Tools", "Data Validation"], None, "{} → {invalid: [cell], truncated: bool (true when the 100,000-cell scan allowance ended before every range was checked)}", has_doc, circle_invalid), CommandSpec { shortcut_mac: Some("Cmd+Shift+K"), diff --git a/crates/engine/src/cmd/data/tests.rs b/crates/engine/src/cmd/data/tests.rs index 524591c946..c4f2eb03b7 100644 --- a/crates/engine/src/cmd/data/tests.rs +++ b/crates/engine/src/cmd/data/tests.rs @@ -557,3 +557,144 @@ fn a_rule_with_an_unknown_type_operator_or_error_style_is_refused() { assert_eq!(sh.validations.len(), 3); assert!(check_validation(&s.doc().unwrap().wb, 0, CellRef::parse("A2").unwrap(), "0").is_some()); } + +fn finds(item: &str, typed: &str) -> bool { + search_matches(&search_fold(item), &search_term(typed)) +} + +#[test] +fn list_search_matches_from_a_word_start() { + let la = "Los Angeles - United States of America"; + for ok in ["Los an", " Los an", "Ange", "United St", "united st", "of America", "- United", "", "L"] { + assert!(finds(la, ok), "{ok:?} should match"); + } + for bad in ["United Amer", "geles", "os", "States America", "Los Angeles -"] { + assert!(!finds(la, bad), "{bad:?} should not match"); + } + // A word start can hide behind an earlier, overlapping occurrence. + assert!(finds("xa-a-a", "a-a")); + assert!(finds("(USA)", "usa")); + assert!(finds("2024 report", "202")); +} + +#[test] +fn list_search_ignores_case_and_accents() { + assert!(finds("États-Unis", "etats")); + assert!(finds("États-Unis", "UNIS")); + assert!(finds("Etats-Unis", "États")); + assert!(finds("Straße", "strasse")); + assert!(finds("Œuvre", "oe")); + assert!(finds("Łódź", "lodz")); + // Decomposed accents (e + combining acute) fold the same and don't start a word. + assert!(finds("Cafe\u{301} noir", "café n")); + assert!(!finds("Cafe\u{301}s", "s")); + assert!(finds("東京", "東")); + // Vietnamese (Latin Extended Additional, with ơ/ư from Latin Extended-B), any case. + assert!(finds("Hà Nội - Vietnam", "ha noi")); + assert!(finds("Đà Nẵng", "da nang")); + assert!(finds("Thừa Thiên Huế", "thua thien hue")); + assert!(finds("HỒ CHÍ MINH", "ho chi")); + assert!(finds("Hồ Chí Minh", "HỒ CHÍ")); + assert!(finds("Phường Bến Nghé", "phuong ben")); + // Pinyin tone marks, transliterations with dots below. + assert!(finds("Běijīng", "beijing")); + assert!(finds("Lǜ", "lu")); + assert!(finds("Ḥaifa", "haifa")); + assert_eq!(search_fold("ỆỢỰẠẞ"), "eouass"); +} + +#[test] +fn filter_list_items_keeps_order_and_cap() { + let items: Vec = ["Dubai - United Arab Emirates", "Paris - France", "London - United Kingdom", "Boston - United States"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(filter_list_items(&items, "United", 100), [0, 2, 3]); + assert_eq!(filter_list_items(&items, "United St", 100), [3]); + assert_eq!(filter_list_items(&items, "United", 2), [0, 2]); + assert!(filter_list_items(&items, "zzz", 100).is_empty()); +} + +#[test] +fn validation_list_command_returns_filtered_items() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "E1", "values": [["Paris - France"], ["Dubai - United Arab Emirates"], ["New York - United States"]]}), + ) + .unwrap(); + s.execute("data.validation", json!({"range": "B2:B5", "type": "list", "formula1": "=$E$1:$E$3"})).unwrap(); + let all = s.execute("data.validationList", json!({"cell": "B3"})).unwrap(); + assert_eq!(all["items"].as_array().map(Vec::len), Some(3)); + assert_eq!(all["truncated"], json!(false)); + let some = s.execute("data.validationList", json!({"cell": "B3", "search": "united s"})).unwrap(); + assert_eq!(some["items"], json!(["New York - United States"])); + assert!(s.execute("data.validationList", json!({"cell": "A1"})).is_err(), "no list validation on A1"); + s.execute("data.validation", json!({"range": "C1", "type": "list", "formula1": "\"Été,Hiver\""})).unwrap(); + let lit = s.execute("data.validationList", json!({"cell": "C1", "search": "ete"})).unwrap(); + assert_eq!(lit["items"], json!(["Été"])); +} + +#[test] +fn validation_list_search_reads_a_huge_source_within_its_budget() { + // A list from a whole column used far past the source budget: a search with no match must + // stop at the budget (and say so) rather than read and fold every cell first. + let mut s = Session::new(); + s.new_workbook(); + let rows = LIST_SOURCE_BUDGET + 5_000; + { + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + for r in 0..rows { + sh.cells.set(CellRef::new(r as u32, 4), Cell::value(Value::Text(format!("Item {r}").into()))); + } + } + s.execute("data.validation", json!({"range": "B2", "type": "list", "formula1": "=$E:$E"})).unwrap(); + let none = s.execute("data.validationList", json!({"cell": "B2", "search": "zzz"})).unwrap(); + assert_eq!(none["items"], json!([])); + assert_eq!(none["truncated"], json!(true), "the source was not read to its end"); + let first = s.execute("data.validationList", json!({"cell": "B2", "search": "item 1"})).unwrap(); + assert_eq!(first["items"][0], json!("Item 1")); + + let wb = s.doc().unwrap().wb.clone(); + let dv = wb.active().unwrap().validations[0].clone(); + let src = list_search_source(&wb, 0, CellRef::new(1, 1), &dv, LIST_SOURCE_BUDGET); + assert!(src.truncated); + assert_eq!(src.items.len(), LIST_SOURCE_BUDGET, "exactly the budget's worth of cells read"); + // The membership check still sees the whole column. + let last = format!("Item {}", rows - 1); + assert!(check_validation(&wb, 0, CellRef::new(1, 1), &last).is_none(), "{last} is in the list"); + // A computed source (a name for a formula) over the same column runs out of formula work instead. + s.execute("formulas.defineName", json!({"name": "Sorted", "refersTo": "=SORT(Sheet1!$E:$E)"})).unwrap(); + s.execute("data.validation", json!({"range": "C2", "type": "list", "formula1": "=Sorted"})).unwrap(); + let sorted = s.execute("data.validationList", json!({"cell": "C2", "search": "zzz"})).unwrap(); + assert_eq!(sorted["truncated"], json!(true)); +} + +#[test] +fn list_search_source_matches_list_items_within_budget() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B1:B5", "values": [["a"], [null], ["c"], ["d"], ["e"]]})).unwrap(); + s.execute("cell.set", json!({"cell": "D1", "input": "=SEQUENCE(4)"})).unwrap(); + s.execute("data.validation", json!({"range": "A1:A2", "type": "list", "formula1": "=$B1:$B4"})).unwrap(); + s.execute("data.validation", json!({"range": "C1", "type": "list", "formula1": "=$D$1:$D$9"})).unwrap(); + s.execute("data.validation", json!({"range": "F1", "type": "list", "formula1": "\"x,y,z\""})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Upper", "refersTo": "=UPPER(Sheet1!$B$1:$B$5)"})).unwrap(); + s.execute("data.validation", json!({"range": "G1", "type": "list", "formula1": "=Upper"})).unwrap(); + let wb = s.doc().unwrap().wb.clone(); + let rules = wb.active().unwrap().validations.clone(); + for (dv, cell) in rules.iter().zip(["A2", "C1", "F1", "G1"]) { + let at = CellRef::parse(cell).unwrap(); + let full = list_items(&wb, 0, at, dv); + assert!(!full.is_empty(), "{cell}"); + let src = list_search_source(&wb, 0, at, dv, LIST_SOURCE_BUDGET); + assert_eq!(src, ListSource { items: full.clone(), truncated: false }, "{cell}"); + // A tiny budget keeps the beginning and says the rest was not read. + let cut = list_search_source(&wb, 0, at, dv, 1); + assert!(cut.truncated, "{cell}: {cut:?}"); + assert!(full.starts_with(&cut.items), "{cell}: {cut:?}"); + } + // The spilled SEQUENCE is read cell by cell like stored values. + assert_eq!(list_search_source(&wb, 0, CellRef::new(0, 2), &rules[1], 100).items, ["1", "2", "3", "4"]); +} diff --git a/crates/engine/src/cmd/data/validation.rs b/crates/engine/src/cmd/data/validation.rs index 31f40491d7..246cf07ecc 100644 --- a/crates/engine/src/cmd/data/validation.rs +++ b/crates/engine/src/cmd/data/validation.rs @@ -269,6 +269,226 @@ pub fn list_items(wb: &Workbook, sheet: usize, at: CellRef, dv: &Validation) -> } } +/// Most entries a searched validation list returns (lists can come from huge ranges). +pub const LIST_MATCH_CAP: usize = 10_000; + +/// Source work a searched validation list may do: cells of its range read (or entries of a literal +/// list, or units of formula work for a computed source). A list from a huge range (`$B:$B` on a +/// sheet used to row 1,048,576) stops here instead of reading every cell, whatever is typed. +pub const LIST_SOURCE_BUDGET: usize = 200_000; + +/// The entries of a list validation read for search, within a source-work budget. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ListSource { + /// Nonempty entries in list order, up to where the budget ran out. + pub items: Vec, + /// The budget ran out before the whole source was read: `items` is only its beginning. + pub truncated: bool, +} + +/// The entries of a list validation for the cell `at`, as [`list_items`] gives them, but reading at +/// most `budget` units of the source (see [`LIST_SOURCE_BUDGET`]). A range source is walked cell by +/// cell, within the sheet's used range, rather than evaluated into an array first. +pub fn list_search_source(wb: &Workbook, sheet: usize, at: CellRef, dv: &Validation, budget: usize) -> ListSource { + let f = dv.f1.trim(); + if is_literal_list(f) { + // A literal list is bounded by the rule's text; the budget still caps the entries kept. + let mut items = list_items(wb, sheet, at, dv); + let truncated = items.len() > budget; + items.truncate(budget); + return ListSource { items, truncated }; + } + let first = RangeRef::top_left(&dv.ranges).unwrap_or(at); + let work = u64::try_from(budget).unwrap_or(u64::MAX); + match gridcraft_calc::evaluate_bounded(wb, sheet, at, &formula_at(f, first, at), work) { + // One area is read as the evaluator would (several areas or sheets are `#VALUE!`: no list). + gridcraft_calc::Bounded::Areas(areas) => match areas.as_slice() { + [a] => walk_area(wb, a.sheet, a.range, budget), + _ => ListSource::default(), + }, + gridcraft_calc::Bounded::Value(Value::Array(a)) => { + let mut out = ListSource::default(); + for (n, v) in a.data.iter().enumerate() { + if n >= budget { + out.truncated = true; + break; + } + if !v.is_empty() { + out.items.push(v.display()); + } + } + out + } + gridcraft_calc::Bounded::Value(v) if !v.is_empty() && !v.is_error() => ListSource { items: vec![v.display()], truncated: false }, + gridcraft_calc::Bounded::Value(_) => ListSource::default(), + gridcraft_calc::Bounded::Exhausted => ListSource { items: vec![], truncated: true }, + } +} + +/// The nonempty values of `range` on `sheet`, row-major, reading at most `budget` cells. Without +/// spilled values in the range only stored cells are visited; with them, every cell inside the +/// sheet's used range (and the spills) is. Each visited cell counts against the budget. +fn walk_area(wb: &Workbook, sheet: usize, range: RangeRef, budget: usize) -> ListSource { + let mut out = ListSource::default(); + let Some(sh) = wb.sheet(sheet) else { return out }; + let spilled = sh.spill_ranges.values().filter_map(|r| r.intersection(&range)).collect::>(); + let mut seen = 0usize; + let mut take = |v: &Value, out: &mut ListSource| { + if seen >= budget { + out.truncated = true; + return false; + } + seen += 1; + if !v.is_empty() { + out.items.push(v.display()); + } + true + }; + if spilled.is_empty() { + for (_, cell) in sh.cells.iter_range(range) { + if !take(&cell.value, &mut out) { + break; + } + } + } else { + let extent = spilled.iter().fold(sh.used_range(), |u, r| Some(u.map_or(*r, |u| u.union(r)))); + let Some(range) = extent.and_then(|u| u.intersection(&range)) else { return out }; + for c in range.iter() { + if !take(&sh.value(c), &mut out) { + break; + } + } + } + out +} + +/// Text folded for list search: lower case, with the accents of Latin letters removed +/// (`É` → `e`, `ß` → `ss`, `Œ` → `oe`, `Ộ` → `o`) and combining marks dropped. Covers Latin-1, +/// Latin Extended-A and -B and Latin Extended Additional; other scripts keep their marks. +pub fn search_fold(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for ch in s.chars().flat_map(char::to_lowercase) { + match fold_latin(ch) { + Some(f) => out.push_str(f), + None => out.push(ch), + } + } + out +} + +/// The unaccented spelling of a lower-case Latin letter (`é` → `e`, `ß` → `ss`, `ộ` → `o`); +/// combining marks fold to nothing. `None` leaves the character as it is. +fn fold_latin(c: char) -> Option<&'static str> { + Some(match c { + '\u{300}'..='\u{36f}' => "", + 'à'..='å' | 'ā' | 'ă' | 'ą' => "a", + 'æ' => "ae", + 'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => "c", + 'ð' | 'ď' | 'đ' => "d", + 'è'..='ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e", + 'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g", + 'ĥ' | 'ħ' => "h", + 'ì'..='ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => "i", + 'ĵ' => "j", + 'ķ' => "k", + 'ĺ' | 'ļ' | 'ľ' | 'ŀ' | 'ł' => "l", + 'ñ' | 'ń' | 'ņ' | 'ň' => "n", + 'ò'..='ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o", + 'œ' => "oe", + 'ŕ' | 'ŗ' | 'ř' => "r", + 'ś' | 'ŝ' | 'ş' | 'š' | 'ș' => "s", + 'ß' => "ss", + 'ţ' | 'ť' | 'ŧ' | 'ț' => "t", + 'þ' => "th", + 'ù'..='ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u", + 'ŵ' => "w", + 'ý' | 'ÿ' | 'ŷ' => "y", + 'ź' | 'ż' | 'ž' => "z", + // Latin Extended-B and Latin Extended Additional (Vietnamese, pinyin tones, …): the base + // letter of each canonical decomposition (Unicode 15). + 'ǎ' | 'ǟ' | 'ǡ' | 'ǻ' | 'ȁ' | 'ȃ' | 'ȧ' | 'ḁ' | 'ạ' | 'ả' | 'ấ' | 'ầ' | 'ẩ' | 'ẫ' | 'ậ' | 'ắ' | 'ằ' | 'ẳ' | 'ẵ' | 'ặ' => { + "a" + } + 'ḃ' | 'ḅ' | 'ḇ' => "b", + 'ḉ' => "c", + 'ḋ' | 'ḍ' | 'ḏ' | 'ḑ' | 'ḓ' => "d", + 'ȅ' | 'ȇ' | 'ȩ' | 'ḕ' | 'ḗ' | 'ḙ' | 'ḛ' | 'ḝ' | 'ẹ' | 'ẻ' | 'ẽ' | 'ế' | 'ề' | 'ể' | 'ễ' | 'ệ' => "e", + 'ḟ' => "f", + 'ǧ' | 'ǵ' | 'ḡ' => "g", + 'ȟ' | 'ḣ' | 'ḥ' | 'ḧ' | 'ḩ' | 'ḫ' | 'ẖ' => "h", + 'ǐ' | 'ȉ' | 'ȋ' | 'ḭ' | 'ḯ' | 'ỉ' | 'ị' => "i", + 'ǰ' => "j", + 'ǩ' | 'ḱ' | 'ḳ' | 'ḵ' => "k", + 'ḷ' | 'ḹ' | 'ḻ' | 'ḽ' => "l", + 'ḿ' | 'ṁ' | 'ṃ' => "m", + 'ǹ' | 'ṅ' | 'ṇ' | 'ṉ' | 'ṋ' => "n", + 'ơ' | 'ǒ' | 'ǫ' | 'ǭ' | 'ȍ' | 'ȏ' | 'ȫ' | 'ȭ' | 'ȯ' | 'ȱ' | 'ṍ' | 'ṏ' | 'ṑ' | 'ṓ' | 'ọ' | 'ỏ' | 'ố' | 'ồ' | 'ổ' | 'ỗ' | 'ộ' | 'ớ' | 'ờ' + | 'ở' | 'ỡ' | 'ợ' => "o", + 'ṕ' | 'ṗ' => "p", + 'ȑ' | 'ȓ' | 'ṙ' | 'ṛ' | 'ṝ' | 'ṟ' => "r", + 'ṡ' | 'ṣ' | 'ṥ' | 'ṧ' | 'ṩ' => "s", + 'ṫ' | 'ṭ' | 'ṯ' | 'ṱ' | 'ẗ' => "t", + 'ư' | 'ǔ' | 'ǖ' | 'ǘ' | 'ǚ' | 'ǜ' | 'ȕ' | 'ȗ' | 'ṳ' | 'ṵ' | 'ṷ' | 'ṹ' | 'ṻ' | 'ụ' | 'ủ' | 'ứ' | 'ừ' | 'ử' | 'ữ' | 'ự' => { + "u" + } + 'ṽ' | 'ṿ' => "v", + 'ẁ' | 'ẃ' | 'ẅ' | 'ẇ' | 'ẉ' | 'ẘ' => "w", + 'ẋ' | 'ẍ' => "x", + 'ȳ' | 'ẏ' | 'ẙ' | 'ỳ' | 'ỵ' | 'ỷ' | 'ỹ' => "y", + 'ẑ' | 'ẓ' | 'ẕ' => "z", + _ => return None, + }) +} + +/// The search term as typed, folded for [`search_matches`]. Leading spaces are ignored. +pub fn search_term(typed: &str) -> String { + search_fold(typed.trim_start()) +} + +/// Whether a folded list entry matches a folded search term, as Excel's in-cell list search: +/// the term appears as one piece that starts at the beginning of a word ("United St" finds +/// "Los Angeles - United States", "geles" and "United Amer" don't). +pub fn search_matches(folded_item: &str, folded_term: &str) -> bool { + if folded_term.is_empty() { + return true; + } + let mut prev: Option = None; + for (i, ch) in folded_item.char_indices() { + if prev.is_none_or(|p| !p.is_alphanumeric()) && folded_item.get(i..).is_some_and(|rest| rest.starts_with(folded_term)) { + return true; + } + prev = Some(ch); + } + false +} + +/// Indices of the list entries matching `typed`, in list order, at most `cap` of them. +pub fn filter_list_items(items: &[String], typed: &str, cap: usize) -> Vec { + let term = search_term(typed); + items.iter().enumerate().filter(|(_, it)| search_matches(&search_fold(it), &term)).map(|(i, _)| i).take(cap).collect() +} + +/// `data.validationList`: a cell's list validation entries, searched like the in-cell dropdown, +/// at most [`LIST_MATCH_CAP`] of them, from at most [`LIST_SOURCE_BUDGET`] of source work. +/// `truncated` says that more entries may exist (past the match cap, or past the source budget). +pub(super) fn validation_list_cmd(s: &mut Session, p: &Json) -> Result { + let d = s.doc()?; + let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active); + let sheet = d.wb.active_sheet(); + let dv = + d.wb.sheet(sheet) + .and_then(|sh| sh.validations.iter().find(|v| v.kind == ValidationKind::List && v.ranges.iter().any(|r| r.contains(at)))) + .ok_or_else(|| EngineError::Other(format!("{} has no list validation", at.a1())))?; + let ListSource { items, truncated: source_truncated } = list_search_source(&d.wb, sheet, at, dv, LIST_SOURCE_BUDGET); + let picked: Vec = match str_param(p, "search") { + Some(term) => filter_list_items(&items, term, LIST_MATCH_CAP.saturating_add(1)), + None => (0..items.len().min(LIST_MATCH_CAP.saturating_add(1))).collect(), + }; + let truncated = source_truncated || picked.len() > LIST_MATCH_CAP; + let out: Vec<&String> = picked.iter().take(LIST_MATCH_CAP).filter_map(|&i| items.get(i)).collect(); + Ok(json!({"items": out, "truncated": truncated})) +} + /// Checks typed input against the validation of a cell. `Ok(None)` = valid. pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -> Option<(Validation, String)> { let sh = wb.sheet(sheet)?; diff --git a/crates/ui-egui/src/app/editing.rs b/crates/ui-egui/src/app/editing.rs index 078f840c0a..6e1ba01a2d 100644 --- a/crates/ui-egui/src/app/editing.rs +++ b/crates/ui-egui/src/app/editing.rs @@ -71,9 +71,23 @@ impl SheetApp { let mut ed = editor::EditState::new(d.uid, d.wb.active_sheet(), at, text, replace, from_formula_bar).on_sheet(&d.wb); ed.window = self.session.active_window(); ed.locale = locale; - if replace && self.ui.autocomplete && !ed.is_formula() { + // A list validation with an in-cell dropdown is searched as the user types; its list + // replaces column AutoComplete. + let list = sh + .validations + .iter() + .find(|v| v.kind == gridcraft_engine::model::ValidationKind::List && v.in_cell_dropdown && v.ranges.iter().any(|r| r.contains(at))); + if let Some(dv) = list { + // Read within a budget: a list from a huge range must not stall the edit it opens. + let budget = gridcraft_engine::cmd::data::LIST_SOURCE_BUDGET; + ed.set_list_source(gridcraft_engine::cmd::data::list_search_source(&d.wb, d.wb.active_sheet(), at, dv, budget), replace); + } else if replace && self.ui.autocomplete && !ed.is_formula() { ed.completion = editor::column_completion(sh, at, &ed.text); } + // Typing over an open dropdown list hands over to the searched list the edit shows; the + // entries it read (and the workbook version they pin) go with it. + self.grid.list_picker = None; + self.grid.list_picker_items = None; self.editor = Some(ed); self.session.mode = if replace { gridcraft_engine::Mode::Enter } else { gridcraft_engine::Mode::Edit }; } @@ -137,9 +151,13 @@ impl SheetApp { if !self.follow_draft_sheet(&mut ed) { return true; } - let text = match &ed.completion { + // Only an explicit acceptance takes the list's entry; a failed commit asks again. + let accepted = std::mem::take(&mut ed.list_accept); + let text = match (ed.list_choice().filter(|_| accepted), &ed.completion) { + // The searched validation list's highlighted entry, as the list spells it. + (Some(choice), _) => choice.to_string(), // A code edit commits the code as typed, whatever a completion holds. - Some(full) if !ed.python && full.to_lowercase().starts_with(&ed.text.to_lowercase()) => full.clone(), + (None, Some(full)) if !ed.python && full.to_lowercase().starts_with(&ed.text.to_lowercase()) => full.clone(), _ => ed.text.clone(), }; // F2 then Enter (or a file command) on an untouched draft: nothing to write. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7d7daf0061..75ccf2f4b6 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -390,6 +390,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - Some(e) => { e.text = s("text").unwrap_or("").to_string(); e.caret = e.text.chars().count(); + e.update_list(); ok(Json::Null) } None => err("not editing"), diff --git a/crates/ui-egui/src/editor.rs b/crates/ui-egui/src/editor.rs index 71fd2a1701..0a9d9a99c8 100644 --- a/crates/ui-egui/src/editor.rs +++ b/crates/ui-egui/src/editor.rs @@ -59,11 +59,54 @@ pub struct EditState { /// The cell's text when an F2-style edit began. Committing it unchanged leaves the cell alone /// (no undo step, the workbook stays clean). `None` for an edit started by typing. pub original: Option, + /// The searchable list of a cell with an in-cell list validation dropdown. + pub list: Option, + /// The user accepted the list's highlighted entry (Enter, Tab or a click on it). Any other + /// commit (clicking elsewhere, a ribbon command, saving) keeps the typed text. + pub list_accept: bool, /// Python mode: the text is a Python cell's code, edited in the formula bar's code editor and /// committed with Ctrl+Enter (Cmd+Enter on macOS) through `python.set`. pub python: bool, } +/// Entries of a list validation, searched as the user types (Excel's searchable dropdown). +#[derive(Clone, Debug, Default)] +pub struct ListSearch { + pub items: Vec, + /// `items` folded for search once, so each keystroke only compares. + folded: Vec, + /// Indices into `items` of the entries matching the typed text, in list order. + pub matches: Vec, + /// The highlighted entry, an index into `matches`. + pub index: usize, + /// Closed with Escape: hidden until the text changes again. + pub closed: bool, + /// First visible row of the popup (an index into `matches`). + pub top: usize, + /// The highlight moved: scroll the popup so it shows. + pub reveal: bool, + /// The list's source was longer than its read budget: `items` holds only its beginning. + pub truncated: bool, + /// Width of the longest of the first matches as the popup measured it, so it is laid out once + /// per search rather than every frame. `None` until measured, and again when the matches change. + pub text_width: Option, +} + +impl ListSearch { + /// Rows the popup shows at once. + pub const VISIBLE: usize = 8; + + /// Scrolls `top` just enough to show the highlighted row. + fn keep_visible(&mut self) { + if self.index < self.top { + self.top = self.index; + } else if self.index >= self.top.saturating_add(Self::VISIBLE) { + self.top = self.index.saturating_add(1).saturating_sub(Self::VISIBLE); + } + self.reveal = true; + } +} + /// A digest of the order of `wb`'s sheets by identity: it changes when a sheet is inserted, /// deleted or moved, not when one is renamed or edited. pub fn sheet_order(wb: &gridcraft_engine::model::Workbook) -> u64 { @@ -99,10 +142,97 @@ impl EditState { caret_to_end: true, completion: None, original, + list: None, + list_accept: false, python: false, } } + /// Gives this edit the entries of its cell's list validation. `search_now` filters them + /// against the text right away (an edit started by typing); otherwise the list waits for + /// the first change (F2 on an existing value). + pub fn set_list_items(&mut self, items: Vec, search_now: bool) { + let folded = items.iter().map(|i| gridcraft_engine::cmd::data::search_fold(i)).collect(); + self.list = Some(ListSearch { items, folded, ..Default::default() }); + if search_now { + self.update_list(); + } + } + + /// Gives this edit a list read within the source budget + /// ([`gridcraft_engine::cmd::data::list_search_source`]), remembering whether it was cut short. + pub fn set_list_source(&mut self, source: gridcraft_engine::cmd::data::ListSource, search_now: bool) { + self.set_list_items(source.items, search_now); + if let Some(l) = self.list.as_mut() { + l.truncated = source.truncated; + } + } + + /// Refilters the list against the typed text (call when the text changes). + pub fn update_list(&mut self) { + let typed = if self.is_formula() || self.text.trim().is_empty() { None } else { Some(self.text.as_str()) }; + let Some(list) = self.list.as_mut() else { return }; + list.matches.clear(); + list.text_width = None; + list.index = 0; + list.top = 0; + list.reveal = true; + list.closed = false; + let Some(typed) = typed else { return }; + let term = gridcraft_engine::cmd::data::search_term(typed); + let cap = gridcraft_engine::cmd::data::LIST_MATCH_CAP; + // Text naming an entry exactly highlights that entry rather than the first match. The + // kept matches stay the first `cap` in list order (as `data.validationList` returns), so + // an exact entry past the cap isn't shown. + let whole = gridcraft_engine::cmd::data::search_fold(typed.trim()); + let mut exact = None; + for (i, f) in list.folded.iter().enumerate() { + if list.matches.len() >= cap { + break; + } + if !gridcraft_engine::cmd::data::search_matches(f, &term) { + continue; + } + if exact.is_none() && *f == whole { + exact = Some(list.matches.len()); + } + list.matches.push(i); + } + if let Some(pos) = exact { + list.index = pos; + list.keep_visible(); + } + } + + /// Whether the searched list is showing (it has matches and wasn't closed). + pub fn list_open(&self) -> bool { + self.list.as_ref().is_some_and(|l| !l.closed && !l.matches.is_empty()) + } + + /// The highlighted entry of the open list: what Enter or Tab commits (see `list_accept`). + pub fn list_choice(&self) -> Option<&str> { + let l = self.list.as_ref().filter(|_| self.list_open())?; + l.matches.get(l.index).and_then(|&i| l.items.get(i)).map(String::as_str) + } + + /// Moves the highlight down (or up), wrapping around. + pub fn list_step(&mut self, down: bool) { + if let Some(l) = self.list.as_mut() + && !l.matches.is_empty() + { + let n = l.matches.len(); + l.index = if down { (l.index + 1) % n } else { (l.index + n - 1) % n }; + l.keep_visible(); + } + } + + /// Hides the list until the text changes (Escape). + pub fn close_list(&mut self) { + if let Some(l) = self.list.as_mut() { + l.closed = true; + } + } + /// An edit of a cell's Python code, in the formula bar. pub fn python(doc: u64, sheet: usize, cell: CellRef, code: String) -> EditState { let mut ed = EditState::new(doc, sheet, cell, code, false, true); @@ -150,6 +280,7 @@ impl EditState { self.point_anchor = None; self.autocomplete.clear(); self.completion = None; + self.list = None; self.caret = self.text.chars().count(); self.anchor = self.caret; self.caret_to_end = false; @@ -541,6 +672,119 @@ mod tests { assert!(ref_is_on_sheet(Some("sheet2"), "Sheet1", "Sheet2"), "sheet names compare ignoring case"); } + fn cities() -> Vec { + ["Dubai - United Arab Emirates", "Paris - France", "London - United Kingdom", "Boston - United States", "Los Angeles - United States"] + .iter() + .map(|s| s.to_string()) + .collect() + } + + fn typed(text: &str) -> EditState { + let mut e = EditState::new(1, 0, CellRef::new(0, 0), text.into(), true, false); + e.set_list_items(cities(), true); + e + } + + #[test] + fn list_search_filters_as_typed_and_picks_the_first_match() { + let mut e = typed("u"); + assert!(e.list_open()); + e.text = "United".into(); + e.update_list(); + assert_eq!(e.list.as_ref().map(|l| l.matches.clone()), Some(vec![0, 2, 3, 4])); + assert_eq!(e.list_choice(), Some("Dubai - United Arab Emirates")); + e.text = "united st".into(); + e.update_list(); + assert_eq!(e.list_choice(), Some("Boston - United States")); + e.list_step(true); + assert_eq!(e.list_choice(), Some("Los Angeles - United States")); + e.list_step(true); + assert_eq!(e.list_choice(), Some("Boston - United States"), "the highlight wraps"); + e.list_step(false); + assert_eq!(e.list_choice(), Some("Los Angeles - United States")); + } + + #[test] + fn list_search_hides_without_matches_formulas_or_text() { + assert!(!typed("Tokyo").list_open()); + assert!(!typed("=A1").list_open()); + assert!(!typed(" ").list_open()); + assert_eq!(typed("Tokyo").list_choice(), None); + } + + #[test] + fn list_search_escape_closes_until_the_text_changes() { + let mut e = typed("Par"); + e.close_list(); + assert!(!e.list_open()); + assert_eq!(e.list_choice(), None, "a closed list commits the typed text"); + e.text = "Pari".into(); + e.update_list(); + assert_eq!(e.list_choice(), Some("Paris - France")); + } + + #[test] + fn list_search_prefers_an_exact_entry() { + let mut e = EditState::new(1, 0, CellRef::new(0, 0), "paris".into(), true, false); + e.set_list_items(vec!["Paris - France".into(), "Paris".into()], true); + assert_eq!(e.list_choice(), Some("Paris")); + } + + #[test] + fn list_search_waits_for_a_change_when_editing_an_existing_value() { + let mut e = EditState::new(1, 0, CellRef::new(0, 0), "Paris - France".into(), false, false); + e.set_list_items(cities(), false); + assert!(!e.list_open(), "F2 doesn't pop the list up"); + e.text = "Paris".into(); + e.update_list(); + assert!(e.list_open()); + } + + #[test] + fn list_search_keeps_the_highlight_in_view() { + let items: Vec = (0..20).map(|i| format!("Item {i}")).collect(); + let mut e = EditState::new(1, 0, CellRef::new(0, 0), "item".into(), true, false); + e.set_list_items(items, true); + for _ in 0..10 { + e.list_step(true); + } + let l = e.list.as_ref().map(|l| (l.index, l.top)).unwrap_or_default(); + assert_eq!(l, (10, 10 + 1 - ListSearch::VISIBLE)); + e.list_step(false); + e.list_step(false); + e.list_step(false); + e.list_step(false); + e.list_step(false); + e.list_step(false); + e.list_step(false); + let l = e.list.as_ref().map(|l| (l.index, l.top)).unwrap_or_default(); + assert_eq!(l, (3, 3)); + } + + #[test] + fn list_search_keeps_list_order_when_the_exact_entry_is_past_the_cap() { + let cap = gridcraft_engine::cmd::data::LIST_MATCH_CAP; + let mut items: Vec = (0..cap + 5).map(|i| format!("Item {i}")).collect(); + items.push("Item".into()); + let mut e = EditState::new(1, 0, CellRef::new(0, 0), "item".into(), true, false); + e.set_list_items(items, true); + let (matches, index) = e.list.as_ref().map(|l| (l.matches.clone(), l.index)).unwrap_or_default(); + assert_eq!(matches, (0..cap).collect::>(), "the first `cap` matches, in list order"); + assert_eq!(index, 0, "the first match stays highlighted"); + assert_eq!(e.list_choice(), Some("Item 0")); + } + + #[test] + fn list_search_highlights_an_exact_entry_within_the_cap() { + let items: Vec = (0..20).map(|i| format!("Item {i}")).chain(["Item".to_string()]).collect(); + let mut e = EditState::new(1, 0, CellRef::new(0, 0), "item".into(), true, false); + e.set_list_items(items, true); + let (index, top) = e.list.as_ref().map(|l| (l.index, l.top)).unwrap_or_default(); + assert_eq!(index, 20); + assert_eq!(top, 21 - ListSearch::VISIBLE, "scrolled into view"); + assert_eq!(e.list_choice(), Some("Item")); + } + #[test] fn whole_row_and_column_ref_spans() { let refs = formula_refs("=SUM(C:C,4:6,$D:$E,Sheet2!7:8)"); diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index 5d54986528..c0805c78c7 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -116,6 +116,10 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) { app.cancel_edit(); } if crate::widgets::icon_button(ui, Icon::Check, c, "Enter", vec2(22.0, 24.0)).clicked() && editing { + // The Enter button is Enter: it takes the searched list's highlighted entry. + if let Some(ed) = app.editor.as_mut() { + ed.list_accept = true; + } app.commit_edit(0, 0, false, false); } let fx = crate::widgets::icon_button(ui, Icon::Fx, t.text, "Insert Function", vec2(26.0, 24.0)); @@ -590,8 +594,10 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: } if resp.changed() { ed.completion = None; + ed.update_list(); // Python code is never completed from the column's text values. if app.ui.autocomplete + && ed.list.is_none() && !ed.is_formula() && !ed.python && !entry_shrank(chars_before, &ed.text) @@ -715,11 +721,18 @@ fn editor_confirm_keys(ui: &mut egui::Ui, ed: &mut crate::editor::EditState) -> if cmd_enter { action = Some((0, 0, false, true)); } + // Enter, Tab and Ctrl+Enter accept the searched list's highlighted entry. + if action.is_some() { + ed.list_accept = true; + } if ctrl_shift_enter { action = Some((0, 0, true, false)); } let cancel = if !esc { false + } else if ed.list_open() { + ed.close_list(); + false } else if !ed.autocomplete.is_empty() { ed.autocomplete.clear(); false @@ -755,6 +768,15 @@ fn editor_arrow_keys( arrow.is_some_and(|(k, _)| k == Key::ArrowRight), ); let (shift, jump) = arrow.map_or((false, false), |(_, m)| (m.shift, m.command)); + if (up || down) && !shift && ed.list_open() { + // The searched validation list takes Up/Down, even in Enter mode. + ui.input_mut(|i| { + i.consume_key(egui::Modifiers::NONE, Key::ArrowUp); + i.consume_key(egui::Modifiers::NONE, Key::ArrowDown); + }); + ed.list_step(down); + return (action, false); + } if (up || down) && !ed.autocomplete.is_empty() { ui.input_mut(|i| { i.consume_key(egui::Modifiers::NONE, Key::ArrowUp); diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 477a4e26af..c52875a247 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -26,7 +26,7 @@ mod active_row; pub use active_row::active_row_band; mod cell_paint; mod cursor; -mod editor; +pub(crate) mod editor; mod geo; mod interact; mod keyboard; @@ -251,6 +251,16 @@ impl Trace { } } +/// The entries of an open list-validation dropdown, read within the list search budget +/// ([`gridcraft_engine::cmd::data::LIST_SOURCE_BUDGET`]). +pub struct ListPickerItems { + /// The workbook version they were read from: any edit makes a new one. + pub(crate) wb: std::sync::Arc, + pub(crate) sheet: usize, + pub(crate) cell: CellRef, + pub source: gridcraft_engine::cmd::data::ListSource, +} + #[derive(Default)] pub struct GridState { /// The active sheet's line positions and outlines, kept with a weak reference to the sheet @@ -304,6 +314,9 @@ pub struct GridState { pub renaming_tab: Option, pub rename_text: String, pub list_picker: Option, + /// The open dropdown's entries, read once for the workbook, sheet and cell they came from, so + /// an open list doesn't read its source again every frame. + pub list_picker_items: Option, /// Open task pane: comments, watch, selection, formatChart. pub pane: Option, /// Ink stroke being drawn (sheet points). diff --git a/crates/ui-egui/src/grid/editor.rs b/crates/ui-egui/src/grid/editor.rs index 72b7cc7bb5..28fb89fc52 100644 --- a/crates/ui-egui/src/grid/editor.rs +++ b/crates/ui-egui/src/grid/editor.rs @@ -1,6 +1,8 @@ use super::cell_paint::ink_on; use super::geo::Geo; -use super::{Align2, CellRef, Color32, FontId, PatternType, Rect, Sheet, SheetApp, Stroke, StrokeKind, Tokens, Workbook, json, pos2, theme, vec2}; +use super::{ + Align2, Arc, CellRef, Color32, FontId, PatternType, Rect, Sheet, SheetApp, Stroke, StrokeKind, Tokens, Workbook, json, pos2, theme, vec2, +}; /// Room the in-cell editor keeps right of its text. It is sized from the text of the last frame, so /// the next typed character must still fit: a fixed 14 px was less than one glyph at high zoom, @@ -108,6 +110,117 @@ const LIST_PICKER_ROW_H: f32 = 18.0; /// Popup frame around the rows: 2 px inner margin and the window stroke on each side, rounded up. const LIST_PICKER_CHROME: f32 = 8.0; +/// Shown under a validation list that was cut short (source budget or match cap). +pub(crate) const LIST_MORE_NOTE: &str = "More entries not shown"; + +/// Height of one row of a validation list popup: its button's real height (text plus padding), at +/// least `LIST_PICKER_ROW_H`. `show_rows` needs the height the rows are drawn at: with a smaller +/// one the popup shows fewer rows than it scrolls by and the last entries can't be reached. +fn list_row_height(ui: &egui::Ui) -> f32 { + LIST_PICKER_ROW_H.max(ui.text_style_height(&egui::TextStyle::Button) + 2.0 * ui.spacing().button_padding.y).ceil() +} + +/// Draws one row of a validation list popup in a slot exactly `row_h` tall. A button sizes itself +/// to its text, and text is laid out to the tallest face its glyphs fall back to, rounded to whole +/// pixels, so its height is not always `list_row_height`. `show_rows` places rows by `row_h`: rows +/// that advance by anything else drift out of the popup and under the note below it. +fn list_row(ui: &mut egui::Ui, width: f32, row_h: f32, button: egui::Button<'_>) -> egui::Response { + let (slot, _) = ui.allocate_exact_size(vec2(width, row_h), egui::Sense::hover()); + // A child placed on the slot: whatever the button asks for, the popup advances by the slot. + let mut row = ui.new_child(egui::UiBuilder::new().max_rect(slot).layout(egui::Layout::top_down(egui::Align::Min))); + row.add(button.min_size(slot.size())) +} + +/// The searched list of a list validation under the cell being typed into (from the cell or the +/// formula bar): the matches of the typed text, the highlighted one is what Enter commits. +pub(super) fn list_search(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) { + let view = app.view_key(); + let Some(ed) = app.editor.as_mut() else { return }; + if view != Some((ed.doc, ed.sheet)) || !ed.list_open() || geo.hidden_under_frozen(sh, ed.cell) { + return; + } + let r = match sh.merge_at(ed.cell) { + Some(m) => geo.range_rect(sh, m), + None => geo.cell_rect(sh, ed.cell), + }; + if !geo.cells.intersects(r) { + return; + } + let Some(list) = ed.list.as_mut() else { return }; + // Rows are as tall as their buttons really are, so `show_rows` places them where they are + // drawn: the popup shows `ListSearch::VISIBLE` of them and the highlighted one stays in view. + let row_h = list_row_height(ui); + // Wide enough for the longest of the first matches, within reason. Measured once per search: + // `update_list` clears it when the matches change. + let longest = match list.text_width { + Some(w) => w, + None => { + let font = egui::TextStyle::Button.resolve(ui.style()); + let w = list + .matches + .iter() + .take(200) + .filter_map(|&i| list.items.get(i)) + .map(|t| ui.painter().layout_no_wrap(t.clone(), font.clone(), Color32::BLACK).size().x) + .fold(0.0_f32, f32::max); + list.text_width = Some(w); + w + } + }; + let width = r.width().max(100.0).max((longest + 16.0).min(480.0)); + // Not every entry was searched (a huge source) or shown (past the match cap). + let more = list.truncated || list.matches.len() >= gridcraft_engine::cmd::data::LIST_MATCH_CAP; + let height = row_h * list.matches.len().clamp(1, crate::editor::ListSearch::VISIBLE) as f32; + let note = if more { row_h } else { 0.0 }; + // Below the cell, or above it when the rows would run past the bottom of the window (as the + // dropdown arrow's list does). + let screen = ui.ctx().content_rect(); + let outer = height + note + LIST_PICKER_CHROME; + let above = r.bottom() + outer > screen.bottom() && r.top() - outer >= screen.top(); + let (at, pivot) = match (above, geo.rtl) { + (false, false) => (geo.mirror_pos(r.left_bottom()), Align2::LEFT_TOP), + (false, true) => (geo.mirror_pos(r.left_bottom()), Align2::RIGHT_TOP), + (true, false) => (geo.mirror_pos(r.left_top()), Align2::LEFT_BOTTOM), + (true, true) => (geo.mirror_pos(r.left_top()), Align2::RIGHT_BOTTOM), + }; + let reveal = std::mem::take(&mut list.reveal).then_some(list.top as f32 * row_h); + let lang = crate::i18n::current(ui.ctx()); + let mut pick = None; + let mut top = None; + egui::Area::new(egui::Id::unique("dv_search")).fixed_pos(at).pivot(pivot).order(egui::Order::Foreground).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).inner_margin(2.0).show(ui, |ui| { + ui.set_min_width(width); + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + ui.spacing_mut().item_spacing.y = 0.0; + let mut area = egui::ScrollArea::vertical().max_height(height).auto_shrink([false, true]); + if let Some(y) = reveal { + area = area.vertical_scroll_offset(y); + } + let out = area.show_rows(ui, row_h, list.matches.len(), |ui, rows| { + for row in rows { + let Some(text) = list.matches.get(row).and_then(|&i| list.items.get(i)) else { continue }; + if list_row(ui, width, row_h, egui::Button::selectable(row == list.index, text.as_str())).clicked() { + pick = Some(row); + } + } + }); + top = Some((out.state.clamped_offset().y / row_h).floor().max(0.0) as usize); + if more { + ui.add_space(2.0); + ui.weak(lang.tr(LIST_MORE_NOTE)); + } + }); + }); + if let Some(top) = top { + list.top = top; + } + if let Some(row) = pick { + list.index = row; + ed.list_accept = true; + app.commit_edit(0, 0, false, false); + } +} + /// Popup height for `n` items: every item up to `LIST_PICKER_MAX_ROWS`, then a scrollbar. pub(super) fn list_picker_height(n: usize, row_h: f32, gap: f32) -> f32 { let rows = n.clamp(1, LIST_PICKER_MAX_ROWS) as f32; @@ -117,45 +230,72 @@ pub(super) fn list_picker_height(n: usize, row_h: f32, gap: f32) -> f32 { /// Draws the validation list popup, choosing above/below and left/right placement for RTL, and applies the clicked item with `cell.set`. pub(super) fn list_picker(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool) { let Some(c) = app.grid.list_picker else { return }; + // An edit shows its own searched list; two lists would stack. + if app.editor.is_some() { + app.grid.list_picker = None; + app.grid.list_picker_items = None; + return; + } let Some(d) = app.session.active() else { return }; let wb = d.wb.clone(); let si = wb.active_sheet(); let Some(sh) = wb.sheet(si) else { return }; - let Some(dv) = sh.validations.iter().find(|x| x.ranges.iter().any(|r| r.contains(c))).cloned() else { + let Some(dv) = sh.validations.iter().find(|x| x.ranges.iter().any(|r| r.contains(c))) else { app.grid.list_picker = None; + app.grid.list_picker_items = None; return; }; - let items = gridcraft_engine::cmd::data::list_items(&wb, si, c, &dv); + // Read the list once while it stays open on the same cell of the same workbook version, and + // within the search budget, so a list over a huge column can't stall every frame. + // Taken out while the popup draws (a click runs a command on `app`), put back below. + let list = match app.grid.list_picker_items.take() { + Some(l) if Arc::ptr_eq(&l.wb, &wb) && l.sheet == si && l.cell == c => l, + _ => { + let budget = gridcraft_engine::cmd::data::LIST_SOURCE_BUDGET; + let source = gridcraft_engine::cmd::data::list_search_source(&wb, si, c, dv, budget); + super::ListPickerItems { wb: wb.clone(), sheet: si, cell: c, source } + } + }; + let (items, truncated) = (&list.source.items, list.source.truncated); let r = geo.cell_rect(sh, c); // Fit the popup to its rows (up to LIST_PICKER_MAX_ROWS); without a minimum the scroll area collapses to its 64 px default. - let height = list_picker_height(items.len(), LIST_PICKER_ROW_H, ui.spacing().item_spacing.y); + let gap = ui.spacing().item_spacing.y; + // A row is as tall as its button really is, so the popup shows LIST_PICKER_MAX_ROWS of them. + let row_h = list_row_height(ui); + let height = list_picker_height(items.len(), row_h, gap); + let note = if truncated { row_h + gap } else { 0.0 }; // Open below the cell, or above it when the rows would run past the bottom of the window (as Excel does). let screen = ui.ctx().content_rect(); - let above = r.bottom() + height + LIST_PICKER_CHROME > screen.bottom() && r.top() - height - LIST_PICKER_CHROME >= screen.top(); + let (outer, top_room) = (height + note + LIST_PICKER_CHROME, r.top() - height - note - LIST_PICKER_CHROME); + let above = r.bottom() + outer > screen.bottom() && top_room >= screen.top(); let (at, pivot) = match (above, geo.rtl) { (false, false) => (geo.mirror_pos(r.left_bottom()), Align2::LEFT_TOP), (false, true) => (geo.mirror_pos(r.left_bottom()), Align2::RIGHT_TOP), (true, false) => (geo.mirror_pos(r.left_top()), Align2::LEFT_BOTTOM), (true, true) => (geo.mirror_pos(r.left_top()), Align2::RIGHT_BOTTOM), }; + let lang = crate::i18n::current(ui.ctx()); let mut close = false; let response = egui::Area::new(egui::Id::unique("dv_list")).fixed_pos(at).pivot(pivot).order(egui::Order::Foreground).show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()).inner_margin(2.0).show(ui, |ui| { ui.set_min_width(r.width().max(100.0)); - egui::ScrollArea::vertical().max_height(height).min_scrolled_height(height).show(ui, |ui| { - for it in &items { - if ui - .add(egui::Button::new(it.as_str()).frame_when_inactive(false).min_size(vec2(r.width().max(100.0), LIST_PICKER_ROW_H))) - .clicked() - { + // Only the rows in view are drawn: a long list costs what eight rows cost. + egui::ScrollArea::vertical().max_height(height).min_scrolled_height(height).show_rows(ui, row_h, items.len(), |ui, rows| { + for it in rows.filter_map(|i| items.get(i)) { + if list_row(ui, r.width().max(100.0), row_h, egui::Button::new(it.as_str()).frame_when_inactive(false)).clicked() { app.run_or_alert("cell.set", json!({"cell": c.a1(), "input": it})); close = true; } } }); + if truncated { + ui.weak(lang.tr(LIST_MORE_NOTE)); + } }); }); if close || popup_dismissed(&response.response, was_open) { app.grid.list_picker = None; + } else { + app.grid.list_picker_items = Some(list); } } diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 97a1d9de6a..713c2d51c7 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -1,6 +1,6 @@ use super::Trace; use super::cursor::update_cursor; -use super::editor::{in_cell_editor, list_picker, validation_arrow}; +use super::editor::{in_cell_editor, list_picker, list_search, validation_arrow}; use super::geo::Geo; use super::interact::{interact, paint_freeze_handles}; use super::menus::{context_menu, error_check_tag, fill_menu, fill_options_tag, filter_menu, header_menu, object_menu}; @@ -379,6 +379,7 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re if app.editor.as_ref().is_some_and(|e| !e.from_formula_bar) { in_cell_editor(app, ui, geo, sh, wb); } + list_search(app, ui, geo, sh); filter_menu(app, ui, geo, previous_popups.0 == app.grid.filter_menu); list_picker(app, ui, geo, previous_popups.1 == app.grid.list_picker); header_menu(app, ui, previous_popups.2 == app.grid.header_menu); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 0e2677e88c..cdc0ebd5f6 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -509,6 +509,20 @@ mod tests { } } + /// The note under a validation list that was cut short is a sentence, not a feature name: a + /// catalog without it shows the English sentence in the middle of a translated interface. + #[test] + fn the_cut_short_list_note_is_translated_in_every_catalog() { + let key = crate::grid::editor::LIST_MORE_NOTE; + for language in Language::ALL { + let shown = language.tr(key); + assert!(!shown.contains('\n'), "{}: {key:?} is not a single line: {shown:?}", language.code()); + if language != Language::En { + assert_ne!(shown, key, "{} falls back to English for {key:?}", language.code()); + } + } + } + /// The Custom Sort dialog's own strings have a row in every catalog (no silent English /// fallback), keep the `{letters}` placeholder, and read as plain English in English. #[test] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 7fbf474c57..830039301e 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -293,6 +293,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Naposledy použité", "No recent workbooks yet." => "Zatím žádné naposledy použité sešity.", "More workbooks" => "Další sešity", + "More entries not shown" => "Další položky nejsou zobrazeny", "Modified" => "Změněno", "Not available" => "Nedostupné", "Just now" => "Právě teď", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index e1490bb96e..0e2656609d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -310,6 +310,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Zuletzt verwendet", "No recent workbooks yet." => "Noch keine zuletzt verwendeten Arbeitsmappen.", "More workbooks" => "Weitere Arbeitsmappen", + "More entries not shown" => "Weitere Elemente werden nicht angezeigt", "Modified" => "Geändert", "Not available" => "Nicht verfügbar", "Just now" => "Gerade eben", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index b5cab06d06..0cdc8c3193 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -280,6 +280,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Πρόσφατα", "No recent workbooks yet." => "Δεν υπάρχουν ακόμη πρόσφατα βιβλία εργασίας.", "More workbooks" => "Περισσότερα βιβλία εργασίας", + "More entries not shown" => "Περισσότερα στοιχεία δεν εμφανίζονται", "Modified" => "Τροποποιήθηκε", "Not available" => "Μη διαθέσιμο", "Just now" => "Μόλις τώρα", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d318e998fc..53d9852a34 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -299,6 +299,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Recientes", "No recent workbooks yet." => "Todavía no hay libros recientes.", "More workbooks" => "Más libros", + "More entries not shown" => "Hay más elementos que no se muestran", "Modified" => "Modificado", "Not available" => "No disponible", "Just now" => "Ahora mismo", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 1fdcb1279c..1ebae6b310 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -386,6 +386,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Récent", "No recent workbooks yet." => "Aucun classeur récent pour le moment.", "More workbooks" => "Plus de classeurs", + "More entries not shown" => "D'autres éléments ne sont pas affichés", "Modified" => "Modifié", "Not available" => "Indisponible", "Just now" => "À l'instant", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1154e17385..11a91de923 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -374,6 +374,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Recenti", "No recent workbooks yet." => "Nessuna cartella di lavoro recente.", "More workbooks" => "Altre cartelle di lavoro", + "More entries not shown" => "Altri elementi non visualizzati", "Modified" => "Modificato", "Not available" => "Non disponibile", "Just now" => "Adesso", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 3033b55e56..46b749e242 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -373,6 +373,7 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Recent", "最近使ったアイテム"), ("No recent workbooks yet.", "最近使ったブックはまだありません。"), ("More workbooks", "その他のブック"), + ("More entries not shown", "表示されていない項目があります"), ("Modified", "更新日時"), ("Not available", "利用できません"), ("Just now", "たった今"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 2e5b7660f0..1c702dc43a 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -386,6 +386,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "최근 항목", "No recent workbooks yet." => "최근 통합 문서가 아직 없습니다.", "More workbooks" => "더 많은 통합 문서", + "More entries not shown" => "표시되지 않은 항목이 더 있습니다", "Modified" => "수정한 날짜", "Not available" => "사용할 수 없음", "Just now" => "방금", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index 8267b65efe..ab4141bf53 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -373,6 +373,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Recent", "No recent workbooks yet." => "Nog geen recente werkmappen.", "More workbooks" => "Meer werkmappen", + "More entries not shown" => "Meer items worden niet weergegeven", "Modified" => "Gewijzigd", "Not available" => "Niet beschikbaar", "Just now" => "Zojuist", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 0b774cbf11..c3a8d79109 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -366,6 +366,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Ostatnie", "No recent workbooks yet." => "Nie masz jeszcze ostatnio używanych skoroszytów.", "More workbooks" => "Więcej skoroszytów", + "More entries not shown" => "Więcej elementów nie jest wyświetlanych", "Modified" => "Zmodyfikowano", "Not available" => "Niedostępne", "Just now" => "Przed chwilą", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index a26216f1ba..f5b63bb074 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -381,6 +381,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Recentes", "No recent workbooks yet." => "Ainda não há pastas de trabalho recentes.", "More workbooks" => "Mais pastas de trabalho", + "More entries not shown" => "Mais itens não exibidos", "Modified" => "Modificado", "Not available" => "Indisponível", "Just now" => "Agora mesmo", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index e4b1ab3c76..4538099e22 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -373,6 +373,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Recente", "No recent workbooks yet." => "Încă niciun registru recent.", "More workbooks" => "Mai multe registre", + "More entries not shown" => "Alte elemente nu sunt afișate", "Modified" => "Modificat", "Not available" => "Indisponibil", "Just now" => "Chiar acum", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index b08802fc32..198e00a3b3 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -385,6 +385,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Последние", "No recent workbooks yet." => "Недавних книг пока нет.", "More workbooks" => "Другие книги", + "More entries not shown" => "Показаны не все элементы", "Modified" => "Изменён", "Not available" => "Недоступен", "Just now" => "Только что", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 5aabbf7b1a..60f509e4b9 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -379,6 +379,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Nedavno", "No recent workbooks yet." => "Još nema nedavnih radnih svezaka.", "More workbooks" => "Više radnih svezaka", + "More entries not shown" => "Još stavki nije prikazano", "Modified" => "Izmenjeno", "Not available" => "Nije dostupno", "Just now" => "Upravo sada", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index ca59a0dd98..aff594a50c 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -286,6 +286,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Son Kullanılanlar", "No recent workbooks yet." => "Henüz son kullanılan çalışma kitabı yok.", "More workbooks" => "Diğer çalışma kitapları", + "More entries not shown" => "Diğer öğeler gösterilmiyor", "Modified" => "Değiştirilme Tarihi", "Not available" => "Kullanılamıyor", "Just now" => "Az önce", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 33141bdfff..0b2ef0121d 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -370,6 +370,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Останні", "No recent workbooks yet." => "Нещодавніх книг поки немає.", "More workbooks" => "Інші книги", + "More entries not shown" => "Показано не всі елементи", "Modified" => "Змінено", "Not available" => "Недоступно", "Just now" => "Щойно", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 100230d026..340ccd214d 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -376,6 +376,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "Gần đây", "No recent workbooks yet." => "Chưa có sổ làm việc gần đây.", "More workbooks" => "Sổ làm việc khác", + "More entries not shown" => "Còn mục khác chưa được hiển thị", "Modified" => "Đã sửa đổi", "Not available" => "Không khả dụng", "Just now" => "Vừa xong", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 36e1d4ccad..66172ab508 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -384,6 +384,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Recent" => "最近", "No recent workbooks yet." => "还没有最近使用的工作簿。", "More workbooks" => "更多工作簿", + "More entries not shown" => "还有更多项未显示", "Modified" => "修改时间", "Not available" => "不可用", "Just now" => "刚刚", diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 83f4b57362..bb69e2e56d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -126,6 +126,7 @@ mod ui_clock; mod undo_while_grouping; mod validation_alert; mod validation_input_message; +mod validation_list_search; mod wheel_zoom; mod whole_line_shortcuts; mod widgets; diff --git a/crates/ui-egui/tests/it/validation_list_search.rs b/crates/ui-egui/tests/it/validation_list_search.rs new file mode 100644 index 0000000000..fc7b2ec811 --- /dev/null +++ b/crates/ui-egui/tests/it/validation_list_search.rs @@ -0,0 +1,367 @@ +//! Typing into a cell with a list validation searches its dropdown: the list shows the entries +//! with a word starting with the typed text, and Enter or Tab takes the highlighted one. + +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::kittest::Queryable; +use gridcraft_engine::Session; +use gridcraft_engine::core::{CellRef, Value}; +use gridcraft_ui_egui::grid; +use serde_json::json; + +use crate::common::{self, Harness}; + +/// A 1200×800 harness on the pinned test font set: row heights must not depend on the fonts the +/// host happens to have installed. +fn open(session: Session) -> Harness { + common::harness_with(common::builder().with_size(egui::vec2(1200.0, 800.0)), common::app(session), 4) +} + +const CITIES: [&str; 6] = [ + "Paris - France", + "Dubai - United Arab Emirates", + "London - United Kingdom", + "Boston - United States of America", + "Los Angeles - United States of America", + "Bogotá - Colombia", +]; + +fn harness_with(rule: serde_json::Value) -> Harness { + let mut session = Session::new(); + session.new_workbook(); + let rows: Vec> = CITIES.iter().map(|c| vec![*c]).collect(); + session.execute("range.setValues", json!({"range": "H1", "values": rows})).unwrap(); + session.execute("data.validation", rule).unwrap(); + session.execute("selection.set", json!({"cell": "B2"})).unwrap(); + open(session) +} + +fn harness() -> Harness { + harness_with(json!({"range": "B2:B9", "type": "list", "formula1": "=$H$1:$H$6"})) +} + +fn key(h: &mut Harness, k: Key, m: Modifiers) { + h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m }); + h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m }); + h.run_steps(2); +} + +fn text(h: &mut Harness, t: &str) { + h.input_mut().events.push(Event::Text(t.into())); + h.run_steps(2); +} + +fn value(h: &Harness, a: &str) -> String { + match h.state().session.active().and_then(|d| d.wb.active().map(|s| s.value(CellRef::parse(a).unwrap_or_default()))) { + Some(Value::Text(t)) => t.to_string(), + Some(v) => v.display(), + None => String::new(), + } +} + +fn active(h: &Harness) -> String { + h.state().session.active().map(|d| d.selection.active.a1()).unwrap_or_default() +} + +fn shown(h: &Harness, item: &str) -> bool { + h.query_by_label(item).is_some() +} + +#[test] +fn typing_filters_the_list_to_entries_with_a_matching_word() { + let mut h = harness(); + text(&mut h, "United"); + assert!(h.state().editor.as_ref().is_some_and(|e| e.list_open()), "typing opens the searched list"); + for city in &CITIES[1..5] { + assert!(shown(&h, city), "{city} matches 'United'"); + } + assert!(!shown(&h, "Paris - France")); + text(&mut h, " St"); + assert!(shown(&h, "Boston - United States of America")); + assert!(shown(&h, "Los Angeles - United States of America")); + assert!(!shown(&h, "London - United Kingdom"), "'United St' narrows to the United States"); + if let Ok(path) = std::env::var("GRIDCRAFT_LIST_SEARCH_SCREENSHOT") { + key(&mut h, Key::ArrowDown, Modifiers::NONE); + h.render().unwrap().save(path).unwrap(); + } +} + +#[test] +fn enter_commits_the_first_match_as_the_list_spells_it() { + let mut h = harness(); + text(&mut h, "united st"); + key(&mut h, Key::Enter, Modifiers::NONE); + assert!(h.state().editor.is_none()); + assert!(h.state().message.is_none(), "no validation alert: the value is a list entry"); + assert_eq!(value(&h, "B2"), "Boston - United States of America"); + assert_eq!(active(&h), "B3"); +} + +#[test] +fn tab_commits_and_moves_right() { + let mut h = harness(); + text(&mut h, "Ange"); + key(&mut h, Key::Tab, Modifiers::NONE); + assert_eq!(value(&h, "B2"), "Los Angeles - United States of America"); + assert_eq!(active(&h), "C2"); +} + +#[test] +fn arrows_move_the_highlight_instead_of_committing() { + let mut h = harness(); + text(&mut h, "United"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert!(h.state().editor.is_some(), "Down moves in the list, it doesn't commit"); + key(&mut h, Key::ArrowUp, Modifiers::NONE); + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, "B2"), "London - United Kingdom"); +} + +#[test] +fn accents_and_case_are_ignored() { + let mut h = harness(); + text(&mut h, "BOGOTA"); + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, "B2"), "Bogotá - Colombia"); +} + +#[test] +fn clicking_an_entry_commits_it() { + let mut h = harness(); + text(&mut h, "United"); + h.get_by_label("London - United Kingdom").click(); + h.run_steps(3); + assert!(h.state().editor.is_none()); + assert_eq!(value(&h, "B2"), "London - United Kingdom"); + assert_eq!(active(&h), "B2"); +} + +#[test] +fn escape_closes_the_list_then_cancels() { + let mut h = harness_with(json!({"range": "B2", "type": "list", "formula1": "=$H$1:$H$6", "errorStyle": "information"})); + text(&mut h, "United"); + key(&mut h, Key::Escape, Modifiers::NONE); + assert!(h.state().editor.as_ref().is_some_and(|e| !e.list_open() && e.text == "United"), "the first Escape only hides the list"); + // With the list closed, Enter keeps the typed text (an Information rule accepts it). + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, "B2"), "United"); + + let mut h = harness(); + text(&mut h, "United"); + key(&mut h, Key::Escape, Modifiers::NONE); + key(&mut h, Key::Escape, Modifiers::NONE); + assert!(h.state().editor.is_none(), "the second Escape cancels the edit"); + assert_eq!(value(&h, "B2"), ""); +} + +#[test] +fn no_match_leaves_the_typed_text_to_validation() { + let mut h = harness(); + text(&mut h, "Tokyo"); + assert!(h.state().editor.as_ref().is_some_and(|e| !e.list_open())); + key(&mut h, Key::Enter, Modifiers::NONE); + assert!(h.state().message.is_some(), "a Stop rule rejects a value outside the list"); + assert_eq!(value(&h, "B2"), ""); +} + +#[test] +fn formulas_are_not_searched() { + let mut h = harness(); + text(&mut h, "=H1"); + assert!(h.state().editor.as_ref().is_some_and(|e| !e.list_open())); +} + +#[test] +fn a_long_list_shows_a_few_rows_and_scrolls_to_the_highlight() { + let mut session = Session::new(); + session.new_workbook(); + let rows: Vec> = (0..50_000).map(|i| vec![format!("Item {i:05}")]).collect(); + session.execute("range.setValues", json!({"range": "H1", "values": rows})).unwrap(); + session.execute("data.validation", json!({"range": "B2", "type": "list", "formula1": "=$H$1:$H$50000"})).unwrap(); + session.execute("selection.set", json!({"cell": "B2"})).unwrap(); + let mut h = open(session); + text(&mut h, "item"); + assert!(shown(&h, "Item 00000")); + assert!(!shown(&h, "Item 00100"), "only the visible rows are drawn"); + for _ in 0..12 { + key(&mut h, Key::ArrowDown, Modifiers::NONE); + } + assert!(shown(&h, "Item 00012"), "the highlighted row scrolls into view"); + assert!(!shown(&h, "Item 00000")); + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, "B2"), "Item 00012"); +} + +#[test] +fn typing_over_the_open_dropdown_replaces_it_with_the_searched_list() { + let mut h = harness(); + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let pos = grid::validation_arrow(sh, &geo, CellRef::parse("B2").unwrap()).unwrap().center(); + h.input_mut().events.push(Event::PointerMoved(pos)); + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().grid.list_picker.is_some(), "the arrow opens the full list"); + assert!(shown(&h, "Paris - France")); + + text(&mut h, "United St"); + assert!(h.state().grid.list_picker.is_none(), "typing closes the full list"); + assert!(h.state().grid.list_picker_items.is_none(), "and drops the entries it read"); + assert!(!shown(&h, "Paris - France"), "only the searched list shows"); + assert_eq!(h.query_all_by_label("Boston - United States of America").count(), 1, "one list, not two"); + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, "B2"), "Boston - United States of America"); + assert!(h.state().grid.list_picker.is_none()); + assert!(!shown(&h, "Boston - United States of America"), "no list is left open after choosing"); +} + +fn click_cell(h: &mut Harness, cell: &str) { + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let pos = geo.cell_rect(sh, CellRef::parse(cell).unwrap()).center(); + h.input_mut().events.push(Event::PointerMoved(pos)); + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn leaving_the_cell_without_accepting_keeps_the_typed_text() { + // An Information rule lets the typed text in, so the commit itself succeeds. + let mut h = harness_with(json!({"range": "B2", "type": "list", "formula1": "=$H$1:$H$6", "errorStyle": "information"})); + text(&mut h, "United"); + assert!(h.state().editor.as_ref().is_some_and(|e| e.list_open())); + click_cell(&mut h, "E2"); // beside the cell: the popup hangs below it + assert!(h.state().editor.is_none(), "clicking another cell commits the edit"); + assert_eq!(value(&h, "B2"), "United", "only Enter, Tab or a click on the list takes its entry"); + + // Ctrl+Enter is an Enter: it takes the highlighted entry. + let mut h = harness(); + text(&mut h, "Ange"); + key(&mut h, Key::Enter, Modifiers::COMMAND); + assert_eq!(value(&h, "B2"), "Los Angeles - United States of America"); +} + +#[test] +fn the_formula_bar_enter_button_takes_the_highlighted_entry() { + let mut h = harness(); + text(&mut h, "united st"); + // The ✓ button sits right of the Name Box (118 wide), after the ✕ button: both are 22 wide + // with 4-point gaps. The Name Box is the leftmost text field; its text starts 6 points in. + let name_box = h.get_all_by_role(egui::accesskit::Role::TextInput).map(|n| n.rect()).min_by(|a, b| a.left().total_cmp(&b.left())).unwrap(); + let pos = egui::pos2(name_box.left() - 6.0 + 118.0 + 4.0 + 4.0 + 4.0 + 22.0 + 4.0 + 11.0, name_box.center().y); + h.input_mut().events.push(Event::PointerMoved(pos)); + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(h.state().editor.is_none(), "the Enter button commits"); + assert!(h.state().message.is_none(), "no validation alert: the list entry was taken"); + assert_eq!(value(&h, "B2"), "Boston - United States of America"); + assert_eq!(active(&h), "B2", "the Enter button doesn't move the selection"); +} + +#[test] +fn a_list_from_a_huge_column_is_read_within_the_source_budget() { + // Typing into a cell whose list is a whole column used far past the budget reads only the + // budget's worth of it, and the edit knows the list was cut short. + let budget = gridcraft_engine::cmd::data::LIST_SOURCE_BUDGET; + let rows: Vec> = (0..budget + 1_000).map(|r| vec![format!("Item {r}")]).collect(); + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": "H1", "values": rows})).unwrap(); + session.execute("data.validation", json!({"range": "B2", "type": "list", "formula1": "=$H:$H"})).unwrap(); + session.execute("selection.set", json!({"cell": "B2"})).unwrap(); + let mut h = open(session); + text(&mut h, "zzz"); + let list = h.state().editor.as_ref().and_then(|e| e.list.as_ref()).map(|l| (l.items.len(), l.truncated, l.matches.len())); + assert_eq!(list, Some((budget, true, 0))); +} + +#[test] +fn the_dropdown_arrow_reads_a_huge_list_once_and_draws_only_its_visible_rows() { + // The full list the arrow opens comes from a whole column used far past the search budget: it + // is read once within the budget (not again every frame) and only the rows in view are drawn. + let budget = gridcraft_engine::cmd::data::LIST_SOURCE_BUDGET; + let rows: Vec> = (0..budget + 1_000).map(|r| vec![format!("Item {r}")]).collect(); + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": "H1", "values": rows})).unwrap(); + session.execute("data.validation", json!({"range": "B2", "type": "list", "formula1": "=$H:$H"})).unwrap(); + session.execute("selection.set", json!({"cell": "B2"})).unwrap(); + let mut h = open(session); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.state().grid.list_picker.is_some(), "Alt+Down opens the full list"); + let read = |h: &Harness| h.state().grid.list_picker_items.as_ref().map(|l| (l.source.items.len(), l.source.truncated, l.source.items.as_ptr())); + let first = read(&h); + assert_eq!(first.map(|(n, t, _)| (n, t)), Some((budget, true))); + h.run_steps(3); + assert_eq!(read(&h), first, "the open list is not read again"); + assert!(shown(&h, "Item 0")); + assert!(!shown(&h, "Item 500"), "rows out of view are not drawn"); + assert!(shown(&h, "More entries not shown")); + key(&mut h, Key::Escape, Modifiers::NONE); + assert!(h.state().grid.list_picker.is_none()); + assert!(h.state().grid.list_picker_items.is_none(), "closing drops the list"); +} + +#[test] +fn the_highlighted_row_stays_inside_the_popup() { + // 50,000 entries match "item": the list is cut at the match cap, so the note sits right under + // the rows. A highlighted row drawn below the note's top is outside the popup's visible rows + // (rows used to be laid out 18 px apart while drawn 24 px tall). + let mut session = Session::new(); + session.new_workbook(); + let rows: Vec> = (0..50_000).map(|i| vec![format!("Item {i:05}")]).collect(); + session.execute("range.setValues", json!({"range": "H1", "values": rows})).unwrap(); + session.execute("data.validation", json!({"range": "B2", "type": "list", "formula1": "=$H$1:$H$50000"})).unwrap(); + session.execute("selection.set", json!({"cell": "B2"})).unwrap(); + let mut h = open(session); + text(&mut h, "item"); + let inside = |h: &Harness, item: &str| { + let row = h.get_by_label(item).rect(); + let note = h.get_by_label("More entries not shown").rect(); + assert!(row.bottom() <= note.top() + 0.5, "{item} at {row:?} runs under the note at {note:?}"); + }; + let visible = gridcraft_ui_egui::editor::ListSearch::VISIBLE; + for _ in 1..visible { + key(&mut h, Key::ArrowDown, Modifiers::NONE); + } + // The last row that fits without scrolling. + inside(&h, &format!("Item {:05}", visible - 1)); + assert!(shown(&h, "Item 00000"), "the list did not need to scroll yet"); + // Up from the first entry wraps to the last kept match: the end of the list is reachable. + for _ in 1..visible { + key(&mut h, Key::ArrowUp, Modifiers::NONE); + } + key(&mut h, Key::ArrowUp, Modifiers::NONE); + let last = format!("Item {:05}", gridcraft_engine::cmd::data::LIST_MATCH_CAP - 1); + inside(&h, &last); + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, "B2"), last); +} + +#[test] +fn the_searched_list_opens_above_a_cell_near_the_bottom_of_the_window() { + let mut h = harness_with(json!({"range": "B2:B200", "type": "list", "formula1": "=$H$1:$H$6"})); + // The last row of column B that is wholly in view. + let (cell, top) = { + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let rect = app.grid.rect.unwrap(); + let geo = grid::Geo::new(sh, rect, app.view().scroll); + let row = (1..200).take_while(|&r| geo.cell_rect(sh, CellRef::new(r, 1)).bottom() <= rect.bottom()).last().unwrap(); + let cell = CellRef::new(row, 1); + (cell, geo.cell_rect(sh, cell).top()) + }; + h.state_mut().session.execute("selection.set", json!({"cell": cell.a1()})).unwrap(); + h.run_steps(2); + text(&mut h, "united"); + let row = h.get_by_label("Boston - United States of America").rect(); + assert!(row.bottom() <= top + 0.5, "the list at {row:?} is above the cell (top {top})"); + assert!(row.top() >= 0.0); + key(&mut h, Key::Enter, Modifiers::NONE); + assert_eq!(value(&h, &cell.a1()), "Dubai - United Arab Emirates"); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c83f8d82bd..a614fb165a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -64,6 +64,7 @@ this logic, with one undo step. | Number-format colors (`[Green]`, `[Color1]`–`[Color56]`) | Rendered in grid and PDF from shared RGB mappings (#1452) | | Point mode (click/drag/arrow references), reference colouring, F4 | done | | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | +| Searchable data validation dropdown (typing filters the in-cell list) | done (10-21): entries with a word starting with the typed text, ignoring case and the accents of Latin letters (é, ç, ß, ł, ș, ǎ, Vietnamese ộ: Latin-1, Latin Extended-A and -B, Latin Extended Additional; other scripts keep their marks), in list order; Up/Down highlight, Enter/Tab/Ctrl+Enter/click commit the highlighted entry as the list spells it (other commits, such as clicking another cell, keep the typed text), Escape hides the list then cancels; `data.validationList {cell, search?}` gives agents the same search. The search reads at most 200,000 cells of the list's source and keeps at most 10,000 matches; past either, `truncated` is set and the popup says more entries aren't shown (validation itself still checks the whole list). Fuzzy matching isn't offered (Excel doesn't either); behaviour follows the documented Excel 365 feature, not yet measured against the app | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | | Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog | @@ -270,6 +271,10 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | The rows of both validation list popups are drawn in slots of exactly the row height the popup scrolls by, so a font whose text is laid out a pixel taller than its nominal line height no longer pushes the last visible row under the "More entries not shown" note (seen with the pinned test fonts, not with the fonts of a desktop install). That note is translated in all 18 interface catalogs, and the validation-list UI tests run on the pinned font set | +| 2026-11-14 | minor | The searched validation list measures its rows at their real height, like the dropdown arrow's list: it shows eight rows instead of six, the highlighted row stays in view and the last entries of a long list can be reached. It opens above the cell when it would run past the bottom of the window, measures its width once per search instead of every frame, and its "More entries not shown" note goes through the interface translations. Typing over the open dropdown drops the entries the dropdown had read | +| 2026-11-13 | minor | The full list the dropdown arrow (or Alt+Down) opens reads its source once while it stays open, within the same 200,000-cell budget, and draws only the rows in view, so a list over a huge column no longer rereads and redraws every entry each frame; it says when entries aren't shown, and its rows are measured at their real height so eight show, as intended | +| 2026-11-13 | minor | A searched validation list reads at most 200,000 cells of its source (`LIST_SOURCE_BUDGET`), walking a range source within the used range instead of evaluating it whole, so a list over a huge or whole column can't stall the edit; `data.validationList` reports `truncated` and the popup says when entries aren't shown | | 2026-11-05 | minor | Reconcile upstream form-control coverage with the CJK baseline and cell-alignment updates | | 2026-11-04 | minor | Keep centered emoji and symbol fallback placement when a row starts with a fallback or contains only fallbacks; use primary or baseline-aligned glyphs to anchor cell alignment | | 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines | @@ -329,6 +334,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-22 | minor | One native window per workbook window on the desktop: per-window drafts, dialogs and ribbons; menu bar commands go to the focused window; closing one of several windows on a workbook doesn't ask; Quit asks in each unsaved workbook's window; the last window closed quits (Windows, Linux) or leaves macOS running | | 2026-10-22 | minor | New Window opens a second window on the same workbook instead of a copy that saved over the original; windows keep their own selection, sheet and scroll; titles Name:1 / Name:2; Switch Windows, Hide and Unhide work by window; File › Close closes one window of several without asking | | 2026-10-22 | minor | New workbook no longer loses the first one: the cell being typed is entered into its own workbook before any File or window command (an entry the workbook refuses stays open and the command doesn't run; an untouched F2 draft changes nothing), the editor is tied to its workbook, View › Switch Windows and the macOS Window menu list the open workbooks, and the macOS Quit item asks about unsaved workbooks like the close button | +| 2026-10-21 | minor | Typing into a cell with an in-cell list validation shows the list filtered to entries with a word starting with the typed text (case and Latin accents ignored, Vietnamese included, list order kept, only visible rows drawn); Up/Down move the highlight, Enter/Tab/click commit it with the list's spelling, Escape hides the list before cancelling. Column AutoComplete is off for those cells. New query command `data.validationList` | | 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel | | 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen | | 2026-10-21 | minor | Form dialogs (conditional-format quick rules, New Name, Remove Duplicates, Text to Columns and every other `Dialog::form`) fit their content: OK and Cancel sit in a row under the last field instead of a right-to-left layout that took the screen's whole height and left the buttons floating halfway down | From 1b92ec071e407895f4245b238bf4063ef1efdb68 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 24 Nov 2026 00:52:03 +0100 Subject: [PATCH 09/10] PivotTables: Distinct Count as a value summary (#3385) * PivotTables: Distinct Count as a value summary (#3336) Co-Authored-By: Claude Sonnet 5.5 * Pivot: refuse Distinct Count for calculated fields A calculated field is evaluated on the report totals, so there are no per-record values to count. pivot.addField and pivot.valueSettings now reject the combination. Co-Authored-By: Claude Sonnet 5.5 * PivotTables: do not offer Distinct Count for a calculated field in the field menu Co-Authored-By: Claude Sonnet 5.5 * fix(xlsx): keep pivot Distinct Count through a save (#3336) SpreadsheetML has no distinct-count subtotal, so a Distinct Count value field is still written as subtotal="count", now with a GridCraft dataField extension that reads back as Distinct Count. A field with Rank as well gets both extensions. The cache of such a PivotTable is written without refreshOnLoad, so Excel opens it showing the computed distinct counts on the sheet; a manual Refresh in Excel recomputes the field as Count. Co-Authored-By: Claude Opus 5.5 * PivotTables: tell the user on .xlsx export that Distinct Count is read only by GridCraft (#3336) Co-Authored-By: Claude Sonnet 5.5 * PivotTables: disclose a new Distinct Count field on an ordinary Save too (#3336) The notice no longer depends on the save path being new: the document remembers which Distinct Count value fields an .xlsx save already reported. Co-Authored-By: Claude Sonnet 5.5 * i18n: translate the Distinct Count strings in every catalog (#3336) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: skylartaylor --- crates/engine/src/cmd/file.rs | 32 +++++++ crates/engine/src/cmd/pivot.rs | 2 +- crates/engine/src/cmd/pivot/fields.rs | 10 +++ crates/engine/src/cmd/pivot/params.rs | 2 + crates/engine/src/cmd/pivot/tests.rs | 120 ++++++++++++++++++++++++++ crates/engine/src/lib.rs | 4 + crates/engine/src/pivot/compute.rs | 14 +-- crates/engine/src/pivot/items.rs | 31 ++++++- crates/model/src/features/pivot.rs | 3 + crates/ui-egui/src/i18n/cs.rs | 6 ++ crates/ui-egui/src/i18n/de.rs | 6 ++ crates/ui-egui/src/i18n/el.rs | 6 ++ crates/ui-egui/src/i18n/es.rs | 6 ++ crates/ui-egui/src/i18n/fr.rs | 6 ++ crates/ui-egui/src/i18n/it.rs | 6 ++ crates/ui-egui/src/i18n/ja.rs | 7 ++ crates/ui-egui/src/i18n/ko.rs | 6 ++ crates/ui-egui/src/i18n/nl.rs | 6 ++ crates/ui-egui/src/i18n/pl.rs | 6 ++ crates/ui-egui/src/i18n/pt.rs | 6 ++ crates/ui-egui/src/i18n/ro.rs | 6 ++ crates/ui-egui/src/i18n/ru.rs | 6 ++ crates/ui-egui/src/i18n/sr.rs | 6 ++ crates/ui-egui/src/i18n/tr.rs | 6 ++ crates/ui-egui/src/i18n/uk.rs | 6 ++ crates/ui-egui/src/i18n/vi.rs | 6 ++ crates/ui-egui/src/i18n/zh.rs | 6 ++ crates/ui-egui/src/pivot_pane.rs | 12 +++ crates/xlsx/src/pivot.rs | 17 ++++ crates/xlsx/src/pivot/read.rs | 20 +++-- crates/xlsx/src/pivot/write.rs | 27 ++++-- crates/xlsx/src/tests/pivot_tests.rs | 74 ++++++++++++++++ 32 files changed, 454 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index aafb0850de..5479b438e0 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -130,6 +130,13 @@ fn save(s: &mut Session, p: &Json) -> Result { None => crate::io::save_bytes(wb, &path)?, }; crate::io::write_file(&path, &bytes)?; + // Only a field the user was not told about yet raises the notice: a known path is no proof, + // since a Distinct Count added after an earlier save is still unreported. + let distinct = distinct_count_fields(wb); + let distinct_notice = kind == Some(crate::io::FileKind::Xlsx) && distinct.iter().any(|f| !d.distinct_disclosed.contains(f)); + if kind == Some(crate::io::FileKind::Xlsx) { + d.distinct_disclosed = distinct; + } // Only a full-fidelity format clears the dirty flag and becomes the document's file. if matches!(kind, Some(crate::io::FileKind::Xlsx | crate::io::FileKind::Json)) { // The new file is the workbook's own now, so `CELL("filename")` reports it (#1489). Set @@ -142,9 +149,31 @@ fn save(s: &mut Session, p: &Json) -> Result { d.saved = d.wb.clone(); d.path = Some(path.clone()); } + if distinct_notice { + s.ui_requests.push(crate::UiRequest::Message(DISTINCT_COUNT_NOTICE.into())); + } Ok(json!({"path": path, "bytes": bytes.len()})) } +/// Shown when a workbook with a Distinct Count PivotTable value field is saved as .xlsx for the first time (#3336): the +/// file stores a plain Count that only GridCraft's private marker turns back into Distinct Count. +const DISTINCT_COUNT_NOTICE: &str = "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count."; + +/// Every Distinct Count value field of the workbook, as (sheet, pivot, value) positions. +fn distinct_count_fields(wb: &gridcraft_model::Workbook) -> Vec<(usize, usize, usize)> { + let mut fields = Vec::new(); + for (si, sheet) in wb.sheets.iter().enumerate() { + for (pi, pt) in sheet.pivots.iter().enumerate() { + for (vi, v) in pt.values.iter().enumerate() { + if v.func == gridcraft_model::PivotFunc::DistinctCount { + fields.push((si, pi, vi)); + } + } + } + } + fields +} + fn save_as(s: &mut Session, p: &Json) -> Result { if str_param(p, "path").is_none() { s.ui_requests.push(crate::UiRequest::Dialog("saveAs".into(), json!({}))); @@ -159,6 +188,9 @@ fn save_bytes(s: &mut Session, p: &Json) -> Result { let name = format!("{}.{fmt}", std::path::Path::new(&d.display_title()).file_stem().and_then(|x| x.to_str()).unwrap_or("Book")); // The file name goes into a PivotChart's link to its PivotTable. let bytes = crate::io::save_bytes(&d.wb, &name)?; + if fmt == "xlsx" && !distinct_count_fields(&d.wb).is_empty() { + s.ui_requests.push(crate::UiRequest::Message(DISTINCT_COUNT_NOTICE.into())); + } Ok(json!({"name": name, "base64": crate::io::base64_encode(&bytes), "bytes": bytes.len()})) } diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 1451e2dab3..13f7a3e652 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Add Field", [], None, - "{pivot?, field, area: rows|columns|values|filters, func?: sum|count|average|max|min|product|countNumbers|stdDev|stdDevP|var|varP, name?, position?: index, replace?}", + "{pivot?, field, area: rows|columns|values|filters, func?: sum|count|average|max|min|product|countNumbers|distinctCount|stdDev|stdDevP|var|varP, name?, position?: index, replace?}", has_doc, add_field ), diff --git a/crates/engine/src/cmd/pivot/fields.rs b/crates/engine/src/cmd/pivot/fields.rs index 55036f5410..7d8c729aed 100644 --- a/crates/engine/src/cmd/pivot/fields.rs +++ b/crates/engine/src/cmd/pivot/fields.rs @@ -106,6 +106,10 @@ fn auto_name(f: PivotFunc, field: &str) -> String { format!("{} of {field}", pv::func_caption(f)) } +/// A calculated field is evaluated on the report's totals, not per source record, so there is +/// no set of values to count the distinct members of. +const NO_CALC_DISTINCT: &str = "A calculated field can't use Distinct Count."; + /// Adds `field` to an area (moving it out of the other axis areas). pub(super) struct AreaPlacement<'a> { pub cmd: &'a str, @@ -140,6 +144,9 @@ pub(super) fn add_to_area(pt: &mut PivotTable, src: &pv::Source, placement: Area } let numeric = is_calc || src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false); let f = func.unwrap_or(if numeric { PivotFunc::Sum } else { PivotFunc::Count }); + if is_calc && f == PivotFunc::DistinctCount { + return Err(other(NO_CALC_DISTINCT)); + } let base = match name { Some(n) if !n.trim().is_empty() => { if src.col(n).is_some() { @@ -506,6 +513,9 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result { let cur = pt.values.get(i).cloned().ok_or_else(|| bad(C, "no value field at that index"))?; let mut v = cur.clone(); if let Some(f) = func { + if f == PivotFunc::DistinctCount && src.col(&cur.source_col).is_none() && calc_field(pt, &cur.source_col).is_some() { + return Err(other(NO_CALC_DISTINCT)); + } v.func = f; // An automatic caption follows the function. Count Numbers was captioned "Count // Numbers of …" before it took Excel's "Count of …", and saved workbooks still carry it. diff --git a/crates/engine/src/cmd/pivot/params.rs b/crates/engine/src/cmd/pivot/params.rs index b257621d8b..0cd3883cda 100644 --- a/crates/engine/src/cmd/pivot/params.rs +++ b/crates/engine/src/cmd/pivot/params.rs @@ -20,6 +20,7 @@ pub(super) fn func_param(v: Option<&str>) -> Option { "min" => PivotFunc::Min, "product" => PivotFunc::Product, "countnumbers" | "countnums" | "count numbers" => PivotFunc::CountNumbers, + "distinctcount" | "distinct count" | "distinct" => PivotFunc::DistinctCount, "stddev" => PivotFunc::StdDev, "stddevp" => PivotFunc::StdDevP, "var" => PivotFunc::Var, @@ -37,6 +38,7 @@ pub(super) fn func_name(f: PivotFunc) -> &'static str { PivotFunc::Min => "min", PivotFunc::Product => "product", PivotFunc::CountNumbers => "countNumbers", + PivotFunc::DistinctCount => "distinctCount", PivotFunc::StdDev => "stdDev", PivotFunc::StdDevP => "stdDevP", PivotFunc::Var => "var", diff --git a/crates/engine/src/cmd/pivot/tests.rs b/crates/engine/src/cmd/pivot/tests.rs index 93ad9868cf..3c697f6236 100644 --- a/crates/engine/src/cmd/pivot/tests.rs +++ b/crates/engine/src/cmd/pivot/tests.rs @@ -571,6 +571,25 @@ fn pivot_chart_errors() { assert!(s.doc().unwrap().wb.active().unwrap().charts.is_empty()); } +#[test] +fn a_calculated_field_cannot_use_distinct_count() { + // It is computed from the report's totals, so there are no per-record values to count. + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.calculatedField", json!({"name": "Price", "formula": "Sales / Units"})).unwrap(); + assert_eq!(text(&s, "C3"), "Sum of Price"); + let before = s.doc().unwrap().wb.clone(); + let set = s.execute("pivot.valueSettings", json!({"field": "Price", "func": "distinctCount"})); + assert!(set.unwrap_err().to_string().contains("Distinct Count")); + assert_eq!(s.doc().unwrap().wb, before, "a rejected change leaves the workbook as it was"); + s.execute("pivot.removeField", json!({"field": "Price", "area": "values"})).unwrap(); + let add = s.execute("pivot.addField", json!({"field": "Price", "area": "values", "func": "distinctCount"})); + assert!(add.unwrap_err().to_string().contains("Distinct Count")); + // A source field still takes it, and a calculated field keeps its other functions. + s.execute("pivot.addField", json!({"field": "Product", "area": "values", "func": "distinctCount"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Price", "area": "values", "func": "sum"})).unwrap(); +} + #[test] fn calculated_field_on_sums() { let mut s = sales(); @@ -1429,6 +1448,107 @@ fn legacy_count_numbers_caption_follows_the_function() { } } +#[test] +fn distinct_count_counts_each_different_value_once_per_cell_and_in_the_totals() { + // #3336: Alice, Bob, Alice, Charlie is 3 distinct customers, where Count says 4. Case does not + // make a name different, and an empty cell is not a value. + let mut s = Session::new(); + s.new_workbook(); + let rows = json!([ + ["Region", "Customer"], + ["East", "Alice"], + ["East", "Bob"], + ["East", "alice"], + ["East", null], + ["West", "Alice"], + ["West", "Charlie"] + ]); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + let make = json!({"source": "Sheet1!$A$1:$B$7", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]}); + s.execute("insert.pivotTable", make).unwrap(); + s.execute("pivot.valueSettings", json!({"index": 0, "func": "count"})).unwrap(); + let counts: Vec = ["E4", "E5", "E6"].iter().map(|a| val(&s, a)).collect(); + assert_eq!(counts, [3.0, 2.0, 5.0].map(Value::Number), "Count counts every non-empty cell"); + s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap(); + assert_eq!(text(&s, "E3"), "Distinct Count of Customer"); + let distinct: Vec = ["E4", "E5", "E6"].iter().map(|a| val(&s, a)).collect(); + assert_eq!(distinct, [2.0, 2.0, 3.0].map(Value::Number), "East has Alice and Bob, West Alice and Charlie, 3 in all"); +} + +#[test] +fn distinct_count_survives_an_xlsx_round_trip_and_a_refresh() { + // #3385: saving wrote Distinct Count as Count, so Alice, Bob, Alice became 3 after reopening + // and refreshing. The sheet keeps the computed distinct counts for other readers too. + let mut s = Session::new(); + s.new_workbook(); + let rows = json!([["Region", "Customer"], ["East", "Alice"], ["East", "Bob"], ["East", "alice"], ["West", "Alice"], ["West", "Charlie"]]); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + let make = json!({"source": "Sheet1!$A$1:$B$6", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]}); + s.execute("insert.pivotTable", make).unwrap(); + s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap(); + let cells = ["E4", "E5", "E6"]; + let expected = [2.0, 2.0, 3.0].map(Value::Number); + assert_eq!(cells.map(|a| val(&s, a)), expected); + let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); + + // The written sheet holds the distinct counts, and the cache doesn't ask for a refresh on open. + let (written, _) = gridcraft_xlsx::read_xlsx(&bytes).unwrap(); + let sheet = written.sheet(0).unwrap(); + assert_eq!(cells.map(|a| sheet.value(CellRef::parse(a).unwrap())), expected); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + let mut cache = String::new(); + std::io::Read::read_to_string(&mut z.by_name("xl/pivotCache/pivotCacheDefinition1.xml").unwrap(), &mut cache).unwrap(); + assert!(!cache.contains("refreshOnLoad"), "{cache}"); + + let mut back = Session::new(); + back.execute("file.open", json!({"name": "book.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + assert_eq!(pt(&back).values[0].func, gridcraft_model::PivotFunc::DistinctCount); + back.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap(); + assert_eq!(text(&back, "E3"), "Distinct Count of Customer"); + assert_eq!(cells.map(|a| val(&back, a)), expected, "a refresh after reopening still counts distinct customers"); +} + +#[test] +fn saving_a_distinct_count_pivot_as_xlsx_says_only_gridcraft_reads_it() { + // #3385: the file stores a plain Count; Excel's Refresh turns it into a count, so the user is told. + let notices = + |s: &mut Session| s.take_ui_requests().iter().filter(|r| matches!(r, crate::UiRequest::Message(m) if m.contains("Distinct Count"))).count(); + let dir = std::env::temp_dir().join(format!("gridcraft-distinct-notice-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + s.new_workbook(); + let rows = json!([["Region", "Customer"], ["East", "Alice"], ["East", "Bob"], ["West", "Alice"]]); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + let make = json!({"source": "Sheet1!$A$1:$B$4", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]}); + s.execute("insert.pivotTable", make).unwrap(); + s.take_ui_requests(); + + s.execute("file.saveAs", json!({"path": dir.join("plain.xlsx")})).unwrap(); + assert_eq!(notices(&mut s), 0, "a plain Count is saved as it is"); + + s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap(); + s.execute("file.saveBytes", json!({"format": "csv"})).unwrap(); + s.execute("file.saveAs", json!({"path": dir.join("book.csv")})).unwrap(); + assert_eq!(notices(&mut s), 0, "only an .xlsx file stores the marker"); + s.execute("file.saveAs", json!({"path": dir.join("book.xlsx")})).unwrap(); + assert_eq!(notices(&mut s), 1); + s.execute("file.save", json!({})).unwrap(); + assert_eq!(notices(&mut s), 0, "saving the same file again does not repeat it"); + // The path is known now, but a Distinct Count added later was never disclosed. + s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$4", "destination": "Sheet1!H3", "rows": ["Region"], "values": ["Customer"]})) + .unwrap(); + s.execute("file.save", json!({})).unwrap(); + assert_eq!(notices(&mut s), 0, "a plain Count adds nothing to disclose"); + s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap(); + s.execute("file.save", json!({})).unwrap(); + assert_eq!(notices(&mut s), 1, "a new Distinct Count field is disclosed on an ordinary Save to the same path"); + s.execute("file.save", json!({})).unwrap(); + assert_eq!(notices(&mut s), 0, "and only once"); + s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + assert_eq!(notices(&mut s), 1, "a download is an export too"); + std::fs::remove_dir_all(&dir).unwrap(); +} + /// A defined name with a table's name doesn't stop a PivotTable's table source following a rename /// of the table: a bare source binds to the table first. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d33a020b6a..b4cf67c65b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -225,6 +225,9 @@ pub struct DocState { /// The references `edit.goTo` with `record: true` went to in this document, newest first, /// without names, each area written with its sheet (`Sheet1!B14:C22,Sheet1!F19:G30`). pub go_to_recent: Vec, + /// The Distinct Count PivotTable value fields (sheet, pivot, value) an .xlsx save has already + /// told the user about (#3336), so only a field not yet disclosed raises the notice again. + pub distinct_disclosed: Vec<(usize, usize, usize)>, } static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -362,6 +365,7 @@ impl DocState { touched: None, edits: None, go_to_recent: vec![], + distinct_disclosed: vec![], } } pub fn is_dirty(&self) -> bool { diff --git a/crates/engine/src/pivot/compute.rs b/crates/engine/src/pivot/compute.rs index 2f282c1678..ef9217b541 100644 --- a/crates/engine/src/pivot/compute.rs +++ b/crates/engine/src/pivot/compute.rs @@ -128,10 +128,14 @@ fn aggregate_record( } for row_depth in 0..=row_path.len() { for col_depth in 0..=col_path.len() { - let accs = data - .aggs - .entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec())) - .or_insert_with(|| vec![Acc::default(); input.vals.len() + input.extra.len()]); + let accs = data.aggs.entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec())).or_insert_with(|| { + input + .vals + .iter() + .map(|(_, v)| Acc::for_func(v.func)) + .chain(std::iter::repeat_n(Acc::default(), input.extra.len())) + .collect::>() + }); for (acc, (source, _)) in accs.iter_mut().zip(input.vals) { if let ValSrc::Col(column) = source { acc.add(rec.get(*column).unwrap_or(&Value::Empty)); @@ -687,7 +691,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro } PivotShowAs::Rank => v.number_format.clone(), _ => v.number_format.clone().or_else(|| match v.func { - PivotFunc::Count | PivotFunc::CountNumbers => None, + PivotFunc::Count | PivotFunc::CountNumbers | PivotFunc::DistinctCount => None, _ => { let f = match vs { ValSrc::Col(c) => fmt_of(*c), diff --git a/crates/engine/src/pivot/items.rs b/crates/engine/src/pivot/items.rs index 6dee1dc5a9..dfbea7e99b 100644 --- a/crates/engine/src/pivot/items.rs +++ b/crates/engine/src/pivot/items.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial}; // ---------------------------------------------------------------- items @@ -120,10 +122,35 @@ pub(super) struct Acc { mean: f64, m2: f64, err: Option, + /// The values seen so far, kept only for a Distinct Count accumulator. + distinct: Option>, +} + +/// What makes two values the same for a Distinct Count: text ignores case, like item labels do. +fn distinct_key(v: &Value) -> Option { + Some(match v { + Value::Empty => return None, + Value::Number(n) => format!("n{}", if *n == 0.0 { 0.0 } else { *n }.to_bits()), + Value::Text(t) if t.is_empty() => return None, + Value::Text(t) => format!("t{}", t.to_lowercase()), + Value::Bool(b) => format!("b{b}"), + Value::Error(e) => format!("e{}", e.as_str()), + Value::Array(_) => return distinct_key(&v.scalar()), + }) } impl Acc { + /// An accumulator for value field function `f`: a Distinct Count also remembers each value it saw. + pub(super) fn for_func(f: PivotFunc) -> Self { + Self { distinct: (f == PivotFunc::DistinctCount).then(HashSet::new), ..Self::default() } + } + pub(super) fn add(&mut self, v: &Value) { + if let Some(seen) = &mut self.distinct + && let Some(key) = distinct_key(v) + { + seen.insert(key); + } match v { Value::Empty => {} Value::Number(n) => { @@ -158,6 +185,7 @@ impl Acc { match f { PivotFunc::Count => return Value::number(self.count as f64), PivotFunc::CountNumbers => return Value::number(n), + PivotFunc::DistinctCount => return Value::number(self.distinct.as_ref().map_or(0, HashSet::len) as f64), _ => {} } if let Some(e) = self.err { @@ -192,7 +220,7 @@ impl Acc { Value::number(if f == PivotFunc::VarP { var } else { var.sqrt() }) } } - PivotFunc::Count | PivotFunc::CountNumbers => Value::Empty, + PivotFunc::Count | PivotFunc::CountNumbers | PivotFunc::DistinctCount => Value::Empty, } } } @@ -208,6 +236,7 @@ pub fn func_caption(f: PivotFunc) -> &'static str { PivotFunc::Min => "Min", PivotFunc::Product => "Product", PivotFunc::CountNumbers => "Count", + PivotFunc::DistinctCount => "Distinct Count", PivotFunc::StdDev => "StdDev", PivotFunc::StdDevP => "StdDevp", PivotFunc::Var => "Var", diff --git a/crates/model/src/features/pivot.rs b/crates/model/src/features/pivot.rs index 9a630ef44a..14bb6c159f 100644 --- a/crates/model/src/features/pivot.rs +++ b/crates/model/src/features/pivot.rs @@ -60,6 +60,9 @@ pub enum PivotFunc { Min, Product, CountNumbers, + /// Number of different non-empty values (Excel's Distinct Count, a Data Model summary). + /// A workbook file has no field for it: it is saved as Count. + DistinctCount, StdDev, StdDevP, Var, diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 830039301e..b13e6feee0 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -601,6 +601,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Zobrazit", "Collapse dialog" => "Sbalit dialogové okno", "Expand dialog" => "Rozbalit dialogové okno", + "Distinct Count" => "Počet různých", + "Summarize by Distinct Count" => "Shrnout podle počtu různých", + "A calculated field can't use Distinct Count." => "Počítané pole nemůže používat počet různých.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Tento sešit obsahuje kontingenční tabulku s hodnotovým polem „Počet různých“. V souboru .xlsx se ukládá jako obyčejný Počet spolu se značkou, kterou čte jen GridCraft, takže Aktualizovat v Excelu z něj udělá obyčejný počet." + } "My list has headers" => "Data obsahují záhlaví", "Sort by" => "Seřadit podle", "Then by" => "Potom podle", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0e2656609d..14d7920e21 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -521,6 +521,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Anzeigen", "Collapse dialog" => "Dialogfeld reduzieren", "Expand dialog" => "Dialogfeld erweitern", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Diese Arbeitsmappe enthält eine PivotTable mit einem Wertfeld „Distinkte Anzahl“. In der .xlsx-Datei wird sie als normale Anzahl mit einer Markierung gespeichert, die nur GridCraft liest; Aktualisieren in Excel macht daraus eine normale Anzahl." + } + "Distinct Count" => "Distinkte Anzahl", + "Summarize by Distinct Count" => "Nach Distinkter Anzahl zusammenfassen", + "A calculated field can't use Distinct Count." => "Ein berechnetes Feld kann „Distinkte Anzahl“ nicht verwenden.", "My list has headers" => "Daten haben Überschriften", "Sort by" => "Sortieren nach", "Then by" => "Anschließend nach", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 0cdc8c3193..07c9fdd6f7 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -435,6 +435,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Move to Values" => "Μετακίνηση στις τιμές", "Summarize by Sum" => "Σύνοψη με άθροισμα", "Summarize by Count" => "Σύνοψη με πλήθος", + "Summarize by Distinct Count" => "Σύνοψη με πλήθος διακριτών", "Summarize by Average" => "Σύνοψη με μέσο όρο", "Summarize by Max" => "Σύνοψη με μέγιστο", "Summarize by Min" => "Σύνοψη με ελάχιστο", @@ -1030,6 +1031,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Εμφάνιση", "Collapse dialog" => "Σύμπτυξη παραθύρου διαλόγου", "Expand dialog" => "Ανάπτυξη παραθύρου διαλόγου", + "Distinct Count" => "Πλήθος διακριτών", + "A calculated field can't use Distinct Count." => "Ένα υπολογιζόμενο πεδίο δεν μπορεί να χρησιμοποιήσει πλήθος διακριτών.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Αυτό το βιβλίο εργασίας έχει μια συγκεντρωτική λίστα με πεδίο τιμών «Πλήθος διακριτών». Στο αρχείο .xlsx αποθηκεύεται ως απλό Πλήθος μαζί με έναν δείκτη που διαβάζει μόνο το GridCraft, οπότε η Ανανέωση στο Excel το μετατρέπει σε απλό πλήθος." + } "Numerical Count" => "Αριθμητικό πλήθος", "Minimum" => "Ελάχιστο", "Maximum" => "Μέγιστο", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 53d9852a34..905d1052c1 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -480,6 +480,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Move to Values" => "Mover a valores", "Summarize by Sum" => "Resumir por suma", "Summarize by Count" => "Resumir por cuenta", + "Summarize by Distinct Count" => "Resumir por recuento distinto", "Summarize by Average" => "Resumir por promedio", "Summarize by Max" => "Resumir por máximo", "Summarize by Min" => "Resumir por mínimo", @@ -527,6 +528,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostrar", "Collapse dialog" => "Contraer diálogo", "Expand dialog" => "Expandir diálogo", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Este libro tiene una tabla dinámica con un campo de valor «Recuento distinto». En el archivo .xlsx se guarda como un Recuento normal con una marca que solo lee GridCraft; Actualizar en Excel lo convierte en un recuento normal." + } + "Distinct Count" => "Recuento distinto", + "A calculated field can't use Distinct Count." => "Un campo calculado no puede usar «Recuento distinto».", "My list has headers" => "Mis datos tienen encabezados", "Sort by" => "Ordenar por", "Then by" => "Luego por", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 1ebae6b310..bac02bb674 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -487,6 +487,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Afficher", "Collapse dialog" => "Réduire la boîte de dialogue", "Expand dialog" => "Développer la boîte de dialogue", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Ce classeur contient un tableau croisé dynamique avec un champ de valeur « Nombre distinct ». Dans le fichier .xlsx, il est enregistré comme un simple Nombre, avec un marqueur que seul GridCraft lit ; Actualiser dans Excel le transforme en simple nombre." + } + "Distinct Count" => "Nombre distinct", + "Summarize by Distinct Count" => "Synthétiser par nombre distinct", + "A calculated field can't use Distinct Count." => "Un champ calculé ne peut pas utiliser « Nombre distinct ».", "My list has headers" => "Mes données ont des en-têtes", "Sort by" => "Trier par", "Then by" => "Puis par", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 11a91de923..dffcced0d9 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -687,6 +687,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Description (optional):" => "Descrizione (facoltativa):", "Fits inside the selected cell and moves with its content." => "Si adatta alla cella selezionata e si sposta insieme al suo contenuto.", "Choose a PNG or JPEG no larger than 16 MB." => "Scegli un file PNG o JPEG di dimensioni non superiori a 16 MB.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Questa cartella di lavoro contiene una tabella pivot con un campo valore «Conteggio distinto». Nel file .xlsx è salvato come Conteggio normale con un indicatore che legge solo GridCraft; Aggiorna in Excel lo trasforma in un conteggio normale." + } "About" => "Informazioni", "Contributors" => "Collaboratori", "Models" => "Modelli", @@ -1010,6 +1013,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Move to Values" => "Sposta in Valori", "Summarize by Sum" => "Riepiloga per somma", "Summarize by Count" => "Riepiloga per conteggio", + "Summarize by Distinct Count" => "Riepiloga per conteggio distinto", "Summarize by Average" => "Riepiloga per media", "Summarize by Max" => "Riepiloga per massimo", "Summarize by Min" => "Riepiloga per minimo", @@ -1036,6 +1040,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostra", "Collapse dialog" => "Comprimi finestra di dialogo", "Expand dialog" => "Espandi finestra di dialogo", + "Distinct Count" => "Conteggio distinto", + "A calculated field can't use Distinct Count." => "Un campo calcolato non può usare «Conteggio distinto».", "Numerical Count" => "Conteggio numeri", "Minimum" => "Minimo", "Maximum" => "Massimo", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 46b749e242..6a5883649f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -703,6 +703,13 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Description (optional):", "説明 (省略可能):"), ("Fits inside the selected cell and moves with its content.", "選択したセル内に収まり、内容と一緒に移動します。"), ("Choose a PNG or JPEG no larger than 16 MB.", "16 MB 以下の PNG または JPEG を選択してください。"), + ( + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count.", + "このブックには、値フィールドが「重複を除いた個数」のピボットテーブルがあります。.xlsx ファイルでは通常の個数と GridCraft だけが読み取るマーカーとして保存されるため、Excel で更新すると通常の個数に戻ります。", + ), + ("Distinct Count", "重複を除いた個数"), + ("Summarize by Distinct Count", "重複を除いた個数で集計"), + ("A calculated field can't use Distinct Count.", "集計フィールドでは「重複を除いた個数」を使用できません。"), ("About", "バージョン情報"), ("Contributors", "貢献者"), ("Models", "モデル"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 1c702dc43a..d0aca424a1 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -491,6 +491,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "표시", "Collapse dialog" => "대화 상자 축소", "Expand dialog" => "대화 상자 확장", + "Distinct Count" => "고유 개수", + "Summarize by Distinct Count" => "고유 개수로 요약", + "A calculated field can't use Distinct Count." => "계산 필드에는 고유 개수를 사용할 수 없습니다.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "이 통합 문서에는 값 필드가 '고유 개수'인 피벗 테이블이 있습니다. .xlsx 파일에는 일반 개수와 GridCraft만 읽는 표식으로 저장되므로, Excel에서 새로 고치면 일반 개수로 바뀝니다." + } "My list has headers" => "내 데이터에 머리글 표시", "Sort by" => "정렬 기준", "Then by" => "다음 기준", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index ab4141bf53..220400b3e4 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -562,6 +562,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Weergeven", "Collapse dialog" => "Dialoogvenster samenvouwen", "Expand dialog" => "Dialoogvenster uitvouwen", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Deze werkmap bevat een draaitabel met een waardeveld ‘Uniek aantal’. In het .xlsx-bestand wordt het opgeslagen als een gewoon Aantal met een markering die alleen GridCraft leest; Vernieuwen in Excel maakt er een gewoon aantal van." + } + "Distinct Count" => "Uniek aantal", + "Summarize by Distinct Count" => "Samenvatten op Uniek aantal", + "A calculated field can't use Distinct Count." => "Een berekend veld kan ‘Uniek aantal’ niet gebruiken.", "My list has headers" => "Mijn gegevens bevatten kopteksten", "Sort by" => "Sorteren op", "Then by" => "Vervolgens op", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index c3a8d79109..b3055a32b9 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -998,6 +998,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Move to Values" => "Przenieś do wartości", "Summarize by Sum" => "Podsumuj według: Suma", "Summarize by Count" => "Podsumuj według: Licznik", + "Summarize by Distinct Count" => "Podsumuj według: Licznik unikatowych", "Summarize by Average" => "Podsumuj według: Średnia", "Summarize by Max" => "Podsumuj według: Maksimum", "Summarize by Min" => "Podsumuj według: Minimum", @@ -1024,6 +1025,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Pokaż", "Collapse dialog" => "Zwiń okno dialogowe", "Expand dialog" => "Rozwiń okno dialogowe", + "Distinct Count" => "Licznik unikatowych", + "A calculated field can't use Distinct Count." => "Pole obliczeniowe nie może używać licznika unikatowych.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Ten skoroszyt zawiera tabelę przestawną z polem wartości „Licznik unikatowych”. W pliku .xlsx jest ona zapisana jako zwykły Licznik wraz ze znacznikiem, który odczytuje tylko GridCraft, więc Odśwież w programie Excel zamienia ją w zwykły licznik." + } "Numerical Count" => "Liczba wartości liczbowych", "Minimum" => "Minimum", "Maximum" => "Maksimum", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index f5b63bb074..f82dba498e 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -712,6 +712,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Description (optional):" => "Descrição (opcional):", "Fits inside the selected cell and moves with its content." => "Ajusta-se dentro da célula selecionada e move-se com o conteúdo dela.", "Choose a PNG or JPEG no larger than 16 MB." => "Escolha um PNG ou JPEG de no máximo 16 MB.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Esta pasta de trabalho tem uma tabela dinâmica com um campo de valor «Contagem distinta». No arquivo .xlsx ela é salva como uma Contagem comum, com um marcador que só o GridCraft lê; Atualizar no Excel a transforma em contagem comum." + } "About" => "Sobre", "Contributors" => "Colaboradores", "Models" => "Modelos", @@ -1042,6 +1045,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostrar", "Collapse dialog" => "Recolher caixa de diálogo", "Expand dialog" => "Expandir caixa de diálogo", + "Distinct Count" => "Contagem distinta", + "Summarize by Distinct Count" => "Resumir por contagem distinta", + "A calculated field can't use Distinct Count." => "Um campo calculado não pode usar «Contagem distinta».", "Numerical Count" => "Contagem Numérica", "Minimum" => "Mínimo", "Maximum" => "Máximo", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 4538099e22..63eec7354d 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -1014,6 +1014,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show as Running Total" => "Afișare ca total cumulat", "Summarize by Average" => "Rezumare după medie", "Summarize by Count" => "Rezumare după numărare", + "Summarize by Distinct Count" => "Rezumare după numărare distinctă", "Summarize by Max" => "Rezumare după maxim", "Summarize by Min" => "Rezumare după minim", "Summarize by Sum" => "Rezumare după sumă", @@ -1086,6 +1087,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Afișare", "Collapse dialog" => "Restrângere casetă de dialog", "Expand dialog" => "Extindere casetă de dialog", + "Distinct Count" => "Numărare distinctă", + "A calculated field can't use Distinct Count." => "Un câmp calculat nu poate folosi numărarea distinctă.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Acest registru de lucru conține un tabel pivot cu un câmp de valori „Numărare distinctă”. În fișierul .xlsx este salvat ca o Numărare simplă, împreună cu un marcaj pe care îl citește doar GridCraft, așa că Reîmprospătare în Excel îl transformă într-o numărare simplă." + } "Numerical Count" => "Numărare numerică", "Minimum" => "Minim", "Maximum" => "Maxim", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 198e00a3b3..b8e2794aff 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1062,6 +1062,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Показать", "Collapse dialog" => "Свернуть диалоговое окно", "Expand dialog" => "Развернуть диалоговое окно", + "Distinct Count" => "Число уникальных", + "Summarize by Distinct Count" => "Итоги по числу уникальных", + "A calculated field can't use Distinct Count." => "Вычисляемое поле не может использовать число уникальных.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "В этой книге есть сводная таблица с полем значений «Число уникальных». В файле .xlsx оно сохраняется как обычное Количество вместе с меткой, которую читает только GridCraft, поэтому команда Обновить в Excel превращает его в обычное количество." + } "My list has headers" => "Мои данные содержат заголовки", "Sort by" => "Сортировать по", "Then by" => "Затем по", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 60f509e4b9..947d609607 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -482,6 +482,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Prikaži", "Collapse dialog" => "Skupi dijalog", "Expand dialog" => "Proširi dijalog", + "Distinct Count" => "Broj različitih", + "Summarize by Distinct Count" => "Sažmi po broju različitih", + "A calculated field can't use Distinct Count." => "Izračunato polje ne može koristiti broj različitih.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Ova radna sveska ima zaokretnu tabelu sa poljem vrednosti „Broj različitih“. U .xlsx datoteci čuva se kao običan Broj uz oznaku koju čita samo GridCraft, pa ga Osveži u Excelu pretvara u običan broj." + } "My list has headers" => "Moji podaci imaju zaglavlja", "Sort by" => "Sortiraj po", "Then by" => "Zatim po", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index aff594a50c..776397b137 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -452,6 +452,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Göster", "Collapse dialog" => "İletişim kutusunu daralt", "Expand dialog" => "İletişim kutusunu genişlet", + "Distinct Count" => "Benzersiz Sayı", + "Summarize by Distinct Count" => "Benzersiz Sayıya göre özetle", + "A calculated field can't use Distinct Count." => "Hesaplanmış alan Benzersiz Sayı kullanamaz.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Bu çalışma kitabında değer alanı “Benzersiz Sayı” olan bir PivotTable var. .xlsx dosyasında düz bir Sayı olarak ve yalnızca GridCraft'in okuduğu bir işaretle saklanır; bu yüzden Excel'de Yenile onu düz bir sayıya dönüştürür." + } "My list has headers" => "Verilerimde üst bilgi var", "Sort by" => "Sıralama ölçütü", "Then by" => "Sonra", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 0b2ef0121d..b829cc1b69 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1002,6 +1002,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Move to Values" => "Move to Values", "Summarize by Sum" => "Summarize by Sum", "Summarize by Count" => "Summarize by Count", + "Summarize by Distinct Count" => "Підсумувати за кількістю унікальних", "Summarize by Average" => "Summarize by Average", "Summarize by Max" => "Summarize by Max", "Summarize by Min" => "Summarize by Min", @@ -1028,6 +1029,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Показати", "Collapse dialog" => "Згорнути діалогове вікно", "Expand dialog" => "Розгорнути діалогове вікно", + "Distinct Count" => "Кількість унікальних", + "A calculated field can't use Distinct Count." => "Обчислюване поле не може використовувати кількість унікальних.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Ця книга містить зведену таблицю з полем значень «Кількість унікальних». У файлі .xlsx воно зберігається як звичайна Кількість разом із міткою, яку читає лише GridCraft, тому Оновити в Excel перетворює його на звичайну кількість." + } "Numerical Count" => "Кількість чисел", "Minimum" => "Мінімум", "Maximum" => "Максимум", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 340ccd214d..e0faa0826a 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -452,6 +452,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Hiện", "Collapse dialog" => "Thu gọn hộp thoại", "Expand dialog" => "Mở rộng hộp thoại", + "Distinct Count" => "Đếm riêng biệt", + "Summarize by Distinct Count" => "Tóm tắt theo Đếm riêng biệt", + "A calculated field can't use Distinct Count." => "Trường tính toán không thể dùng Đếm riêng biệt.", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "Sổ làm việc này có PivotTable với trường giá trị “Đếm riêng biệt”. Trong tệp .xlsx, trường này được lưu dưới dạng Đếm thông thường cùng một dấu hiệu mà chỉ GridCraft đọc, nên Làm mới trong Excel sẽ biến nó thành đếm thông thường." + } "My list has headers" => "Dữ liệu của tôi có tiêu đề", "Sort by" => "Sắp xếp theo", "Then by" => "Sau đó theo", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 66172ab508..0c0042fa6c 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -483,6 +483,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "显示", "Collapse dialog" => "折叠对话框", "Expand dialog" => "展开对话框", + "Distinct Count" => "非重复计数", + "Summarize by Distinct Count" => "按非重复计数汇总", + "A calculated field can't use Distinct Count." => "计算字段不能使用非重复计数。", + "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { + "此工作簿中有一个值字段为“非重复计数”的数据透视表。在 .xlsx 文件中,它被保存为普通计数,并附带只有 GridCraft 能读取的标记,因此在 Excel 中刷新会将其变为普通计数。" + } "My list has headers" => "数据包含标题", "Sort by" => "主要关键字", "Then by" => "次要关键字", diff --git a/crates/ui-egui/src/pivot_pane.rs b/crates/ui-egui/src/pivot_pane.rs index ef753fa993..8ea567b195 100644 --- a/crates/ui-egui/src/pivot_pane.rs +++ b/crates/ui-egui/src/pivot_pane.rs @@ -113,13 +113,25 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) { } if *key == "values" { ui.separator(); + // A calculated field is evaluated on the summed fields, so it has no Distinct Count. + let calculated = info["values"] + .as_array() + .and_then(|vs| vs.iter().find(|x| x["name"].as_str() == Some(f.as_str()))) + .and_then(|x| x["field"].as_str()) + .is_some_and(|src| { + fields.iter().any(|c| c["calculated"].as_bool() == Some(true) && c["name"].as_str() == Some(src)) + }); for (func, l) in [ ("sum", "Summarize by Sum"), ("count", "Summarize by Count"), + ("distinctCount", "Summarize by Distinct Count"), ("average", "Summarize by Average"), ("max", "Summarize by Max"), ("min", "Summarize by Min"), ] { + if calculated && func == "distinctCount" { + continue; + } if ui.button(lang.tr(l)).clicked() { app.run_or_alert("pivot.valueSettings", json!({"pivot": name, "field": f, "func": func})); } diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 45a6188933..481c8a5599 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -7,6 +7,14 @@ //! grouping, `fieldGroup` group items) so the table's `` can refer to them. The report //! cells the engine wrote stay on the sheet as plain cells. //! +//! Distinct Count: SpreadsheetML's subtotal list has no distinct count (Excel has one only for +//! PivotTables on its Data Model, whose binary model part we don't write). Such a value field is +//! written as `subtotal="count"` with a GridCraft `extLst` marker ([`EXT_GC_DATA_FIELD`]) that +//! GridCraft reads back as Distinct Count; other readers ignore the unknown extension. The cache +//! of a PivotTable with a Distinct Count field is written without `refreshOnLoad`, so Excel opens +//! it showing the distinct counts already on the sheet. A Refresh in Excel recomputes the field as +//! Count. +//! //! Reading: the cache's source and field names plus the table's areas, functions, show-values-as, //! layout flags, grand totals and style become a model [`PivotTable`]. Anything we don't model //! (OLAP sources, calculated fields, numeric grouping…) becomes a warning. @@ -48,6 +56,10 @@ const MAX_FIELDS: usize = 16_384; const EXT_X14_DATA_FIELD: &str = "{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"; const EXT_X14_PIVOT_TABLE: &str = "{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}"; const NS_X14: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; +/// GridCraft's `dataField` extension: `` marks a value field +/// written as `subtotal="count"` as a Distinct Count (see the module documentation). +const EXT_GC_DATA_FIELD: &str = "{80B1AD42-0C9F-45FF-B109-D57FB0F4F0B4}"; +const NS_GC: &str = "https://github.com/storytold/gridcraft/ns/pivot/2026"; const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; @@ -78,6 +90,10 @@ fn func_name(f: PivotFunc) -> &'static str { PivotFunc::Min => "min", PivotFunc::Product => "product", PivotFunc::CountNumbers => "countNums", + // The file format's subtotal list has no distinct count (Excel keeps it in a Data Model + // extension), so the nearest function is written, with a GridCraft extension that marks + // the field as Distinct Count (see the module documentation). + PivotFunc::DistinctCount => "count", PivotFunc::StdDev => "stdDev", PivotFunc::StdDevP => "stdDevp", PivotFunc::Var => "var", @@ -111,6 +127,7 @@ fn func_caption(f: PivotFunc) -> &'static str { PivotFunc::Min => "Min", PivotFunc::Product => "Product", PivotFunc::CountNumbers => "Count", + PivotFunc::DistinctCount => "Distinct Count", PivotFunc::StdDev => "StdDev", PivotFunc::StdDevP => "StdDevp", PivotFunc::Var => "Var", diff --git a/crates/xlsx/src/pivot/read.rs b/crates/xlsx/src/pivot/read.rs index 5fd1efbcad..61927e972e 100644 --- a/crates/xlsx/src/pivot/read.rs +++ b/crates/xlsx/src/pivot/read.rs @@ -1,6 +1,7 @@ use super::{ - CellRef, Ctx, DateSystem, El, HashMap, IoError, MAX_FIELDS, PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout, - PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet, + CellRef, Ctx, DateSystem, EXT_GC_DATA_FIELD, El, HashMap, IoError, MAX_FIELDS, PivotCalcField, PivotDateGroup, PivotField, PivotFilter, + PivotFunc, PivotLayout, PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, + quote_sheet, }; // ================================================================ reading @@ -368,12 +369,15 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option PivotShowAs::Rank, (Some(other), _) => { diff --git a/crates/xlsx/src/pivot/write.rs b/crates/xlsx/src/pivot/write.rs index a56bbf7078..cea529999d 100644 --- a/crates/xlsx/src/pivot/write.rs +++ b/crates/xlsx/src/pivot/write.rs @@ -133,7 +133,11 @@ impl PivotWriter { } else { None }; - out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), cache_xml(&cache, rec_rid.as_deref(), wb.date_system).into_bytes()); + // A refresh on open would recompute a Distinct Count field as Count (the file format has + // no distinct count), so such a PivotTable opens showing the values on the sheet. + let refresh_on_load = !pt.values.iter().any(|v| v.func == PivotFunc::DistinctCount); + let xml = cache_xml(&cache, rec_rid.as_deref(), wb.date_system, refresh_on_load); + out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), xml.into_bytes()); self.caches.push((n, format!("pivotCache/pivotCacheDefinition{n}.xml"))); self.tables += 1; let t = self.tables; @@ -519,7 +523,7 @@ fn item_xml(v: &Value, sys: DateSystem, date: bool) -> String { } } -fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem) -> String { +fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem, refresh_on_load: bool) -> String { let mut s = format!("{XML_DECL} { @@ -527,7 +531,10 @@ fn cache_xml(c: &Cache, records_rid: Option<&str>, sys: DateSystem) -> String { } _ => s.push_str(" saveData=\"0\""), } - s.push_str(" refreshOnLoad=\"1\" refreshedBy=\"GridCraft\" createdVersion=\"6\" refreshedVersion=\"6\" minRefreshableVersion=\"3\">"); + if refresh_on_load { + s.push_str(" refreshOnLoad=\"1\""); + } + s.push_str(" refreshedBy=\"GridCraft\" createdVersion=\"6\" refreshedVersion=\"6\" minRefreshableVersion=\"3\">"); let _ = write!(s, "{}", c.source_xml); let _ = write!(s, "", c.fields.len()); for f in &c.fields { @@ -875,13 +882,17 @@ fn write_data_fields(s: &mut String, c: &Cache, layout: &PivotTableLayout<'_>, f if let Some(id) = value.number_format.as_deref().and_then(fmt_id) { let _ = write!(s, " numFmtId=\"{id}\""); } + let mut ext = String::new(); if value.show_as == PivotShowAs::Rank { - let _ = write!( - s, - ">" - ); - } else { + let _ = write!(ext, ""); + } + if value.func == PivotFunc::DistinctCount { + let _ = write!(ext, ""); + } + if ext.is_empty() { s.push_str("/>"); + } else { + let _ = write!(s, ">{ext}"); } } s.push_str(""); diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 4489cb441f..300a890653 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -869,3 +869,77 @@ fn two_value_fields_without_columns_hide_the_values_row() { assert!(t.contains("firstHeaderRow=\"1\""), "{t}"); assert!(!t.contains("hideValuesRow"), "{t}"); } + +/// The "Trend" pivot of [`workbook`] with `values` as its value fields, written; returns the file +/// and its PivotTable and cache parts. +fn trend_with(values: impl FnOnce(&PivotValue) -> Vec) -> (Vec, String, String) { + let mut wb = workbook(); + let pivot = wb.sheet_mut(1).unwrap().pivots.iter_mut().find(|p| p.name == "Trend").unwrap(); + pivot.values = values(&pivot.values[0]); + let bytes = write_xlsx(&wb).unwrap(); + let parts = unzip(&bytes); + let (path, table) = parts + .iter() + .filter(|(path, _)| path.starts_with("xl/pivotTables/pivotTable")) + .map(|(path, xml)| (path.clone(), String::from_utf8_lossy(xml).into_owned())) + .find(|(_, xml)| xml.contains("name=\"Trend\"")) + .unwrap(); + let n = path.trim_start_matches("xl/pivotTables/pivotTable").trim_end_matches(".xml"); + let cache_part = format!("xl/pivotCache/pivotCacheDefinition{n}.xml"); + let rels = String::from_utf8_lossy(&parts[&format!("xl/pivotTables/_rels/pivotTable{n}.xml.rels")]).into_owned(); + assert!(rels.contains(&format!("../pivotCache/pivotCacheDefinition{n}.xml")), "{rels}"); + let cache = String::from_utf8_lossy(&parts[&cache_part]).into_owned(); + (bytes, table, cache) +} + +fn trend_values(bytes: &[u8]) -> Vec { + let (back, report) = read_xlsx(bytes).unwrap(); + assert!(report.warnings.iter().all(|w| !w.to_lowercase().contains("pivot")), "{:?}", report.warnings); + back.sheet(1).unwrap().pivots.iter().find(|p| p.name == "Trend").unwrap().values.clone() +} + +const GC_DISTINCT: &str = ""; + +#[test] +fn distinct_count_round_trips_through_a_gridcraft_extension() { + // The file format's subtotal list has no distinct count: the field is written as Count, which + // other readers use, with a GridCraft marker that brings Distinct Count back on open. + let (bytes, table, cache) = + trend_with(|v| vec![PivotValue { func: PivotFunc::DistinctCount, name: "Distinct Count of Sales".into(), ..v.clone() }]); + assert!(table.contains("{GC_DISTINCT}")), "{table}"); + // A refresh on open would recompute it as Count in Excel, over the values on the sheet. + assert!(!cache.contains("refreshOnLoad"), "{cache}"); + let values = trend_values(&bytes); + assert_eq!((values[0].func, values[0].name.as_str()), (PivotFunc::DistinctCount, "Distinct Count of Sales")); +} + +#[test] +fn rank_and_distinct_count_write_one_extension_each() { + let (bytes, table, _) = trend_with(|v| { + vec![PivotValue { func: PivotFunc::DistinctCount, show_as: PivotShowAs::Rank, name: "Rank of Distinct Sales".into(), ..v.clone() }] + }); + let rank = ""; + assert!(table.contains(&format!("{rank}{GC_DISTINCT}")), "{table}"); + let values = trend_values(&bytes); + assert_eq!((values[0].func, values[0].show_as), (PivotFunc::DistinctCount, PivotShowAs::Rank)); +} + +#[test] +fn count_without_the_gridcraft_extension_reads_as_count() { + // Plain `subtotal="count"`, as Excel writes it, stays Count; so does a stale marker on a field + // whose function was changed to something else. + let (bytes, table, cache) = trend_with(|v| vec![PivotValue { func: PivotFunc::Count, name: "Count of Sales".into(), ..v.clone() }]); + assert!(!table.contains("extLst"), "{table}"); + assert!(cache.contains("refreshOnLoad=\"1\""), "{cache}"); + assert_eq!(trend_values(&bytes)[0].func, PivotFunc::Count); + let marked = |subtotal: &str| { + format!( + r#"{GC_DISTINCT}"# + ) + }; + let func = |table: &str| read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap().0.sheet(0).unwrap().pivots[0].values[0].func; + assert_eq!(func(&marked(" subtotal=\"count\"")), PivotFunc::DistinctCount); + assert_eq!(func(&marked("")), PivotFunc::Sum); + assert_eq!(func(&marked(" subtotal=\"max\"")), PivotFunc::Max); +} From 33bb59307b89c3a9fc8e4f20ce7ab4818a994a04 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 24 Nov 2026 19:29:20 -0500 Subject: [PATCH 10/10] packaging(linux): support co-installable nightly packages (#4733) Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch. Co-authored-by: Dylan M. Taylor --- .github/nightly-linux-signing-key.asc | 16 + .github/nightly-signing-policy.json | 107 ++++ .github/workflows/actions.lock | 2 + .github/workflows/nightly-sign.yml | 42 ++ .github/workflows/nightly.yml | 34 ++ .github/workflows/packaging-lint.yml | 23 +- .gitignore | 6 + ATTRIBUTION.md | 6 + Cargo.lock | 1 + README.md | 4 + apps/gridcraft-cli/src/main.rs | 39 ++ apps/gridcraft/Cargo.toml | 2 + apps/gridcraft/build.rs | 54 +- apps/gridcraft/src/app_dirs.rs | 92 +++ apps/gridcraft/src/build_channel.rs | 55 ++ apps/gridcraft/src/build_flavor.rs | 73 +++ apps/gridcraft/src/launch_profile.rs | 223 ++++++++ apps/gridcraft/src/main.rs | 250 +++++++-- apps/gridcraft/src/nightly_session.rs | 310 ++++++++++ apps/gridcraft/src/process_identity.rs | 81 +++ apps/gridcraft/src/profile_root.rs | 528 ++++++++++++++++++ assets/app-icon/README.md | 13 + assets/app-icon/gridcraft-nightly-1024.png | Bin 0 -> 61068 bytes assets/app-icon/gridcraft-nightly.icns | Bin 0 -> 160638 bytes assets/app-icon/gridcraft-nightly.ico | Bin 0 -> 37909 bytes assets/app-icon/gridcraft-nightly.png | Bin 0 -> 15542 bytes assets/app-icon/gridcraft-nightly.svg | 30 + assets/app-icon/nightly-provenance.json | 56 ++ crates/mcp/src/control_auth.rs | 33 +- crates/mcp/src/tests.rs | 9 + crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/prefs.rs | 11 +- crates/ui-egui/src/backstage.rs | 4 +- crates/ui-egui/src/channel.rs | 167 ++++++ crates/ui-egui/src/dialogs/about.rs | 7 +- crates/ui-egui/src/doc_windows.rs | 4 +- crates/ui-egui/src/lib.rs | 1 + docs/nightly-release-preparation.md | 139 +++++ packaging/icons.sh | 3 + packaging/linux/flatpak-bundle.sh | 70 ++- packaging/linux/nfpm.yaml | 13 +- packaging/linux/nightly-arch-launch.sh | 21 + packaging/linux/nightly-arch-tar-test.sh | 65 +++ packaging/linux/nightly-arch-tar.sh | 19 + packaging/linux/nightly-launch.sh | 35 ++ packaging/linux/nightly-linux-launch-tests.py | 263 +++++++++ packaging/linux/nightly.sh | 33 ++ packaging/linux/package.sh | 188 ++++++- packaging/macos/nightly-lib.sh | 117 ++++ packaging/macos/nightly-sign.sh | 144 +++++ packaging/macos/nightly-verify.sh | 74 +++ packaging/macos/nightly.sh | 51 ++ packaging/macos/nightly_plist.py | 69 +++ packaging/macos/nightly_plist_tests.py | 202 +++++++ packaging/macos/nightly_sign_tests.py | 445 +++++++++++++++ packaging/nightly-archive-tests.py | 231 ++++++++ packaging/nightly-archive.py | 132 +++++ packaging/nightly-common.sh | 97 ++++ packaging/nightly-icons.py | 227 ++++++++ packaging/nightly-release-tests.py | 464 +++++++++++++++ packaging/nightly-tests.py | 26 + packaging/nightly_paths.py | 139 +++++ packaging/windows/nightly-package-tests.ps1 | 95 ++++ packaging/windows/nightly-signing-tests.ps1 | 83 +++ packaging/windows/nightly.ps1 | 133 +++++ packaging/windows/package.ps1 | 24 +- packaging/windows/sign.ps1 | 43 +- sonar-project.properties | 8 + 68 files changed, 5842 insertions(+), 95 deletions(-) create mode 100644 .github/nightly-linux-signing-key.asc create mode 100644 .github/nightly-signing-policy.json create mode 100644 .github/workflows/nightly-sign.yml create mode 100644 .github/workflows/nightly.yml create mode 100644 apps/gridcraft/src/app_dirs.rs create mode 100644 apps/gridcraft/src/build_channel.rs create mode 100644 apps/gridcraft/src/build_flavor.rs create mode 100644 apps/gridcraft/src/launch_profile.rs create mode 100644 apps/gridcraft/src/nightly_session.rs create mode 100644 apps/gridcraft/src/process_identity.rs create mode 100644 apps/gridcraft/src/profile_root.rs create mode 100644 assets/app-icon/gridcraft-nightly-1024.png create mode 100644 assets/app-icon/gridcraft-nightly.icns create mode 100644 assets/app-icon/gridcraft-nightly.ico create mode 100644 assets/app-icon/gridcraft-nightly.png create mode 100644 assets/app-icon/gridcraft-nightly.svg create mode 100644 assets/app-icon/nightly-provenance.json create mode 100644 crates/ui-egui/src/channel.rs create mode 100644 docs/nightly-release-preparation.md create mode 100755 packaging/linux/nightly-arch-launch.sh create mode 100755 packaging/linux/nightly-arch-tar-test.sh create mode 100755 packaging/linux/nightly-arch-tar.sh create mode 100755 packaging/linux/nightly-launch.sh create mode 100644 packaging/linux/nightly-linux-launch-tests.py create mode 100755 packaging/linux/nightly.sh create mode 100755 packaging/macos/nightly-lib.sh create mode 100755 packaging/macos/nightly-sign.sh create mode 100755 packaging/macos/nightly-verify.sh create mode 100755 packaging/macos/nightly.sh create mode 100755 packaging/macos/nightly_plist.py create mode 100755 packaging/macos/nightly_plist_tests.py create mode 100755 packaging/macos/nightly_sign_tests.py create mode 100755 packaging/nightly-archive-tests.py create mode 100644 packaging/nightly-archive.py create mode 100644 packaging/nightly-common.sh create mode 100755 packaging/nightly-icons.py create mode 100755 packaging/nightly-release-tests.py create mode 100755 packaging/nightly-tests.py create mode 100644 packaging/nightly_paths.py create mode 100644 packaging/windows/nightly-package-tests.ps1 create mode 100644 packaging/windows/nightly-signing-tests.ps1 create mode 100644 packaging/windows/nightly.ps1 diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 0000000000..a1c1f31e8d --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 0000000000..02d5129b1c --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,107 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/gridcraft", + "repository_id": 1408285582, + "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": "gridcraft-nightly-20261124", + "repository": "storytold/gridcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 380135773, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_gridcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_gridcraft&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" + } + } + } +} diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 6917bde73b..b463b78c5c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -9,6 +9,8 @@ workflows: '.github/workflows/lockfile.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly-sign.yml': [] + '.github/workflows/nightly.yml': [] '.github/workflows/nix.yml': [] '.github/workflows/packaging-lint.yml': - 'actions/checkout@v7.0.1' diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 0000000000..4430db0945 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: GridCraft 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: gridcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/gridcraft' && + 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. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000000..a201ce8588 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: GridCraft 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/gridcraft' && + 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: gridcraft + 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"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 1633071003..a50fde9d8e 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -5,9 +5,9 @@ name: Packaging lint on: push: branches: [main, release] - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"] pull_request: - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"] workflow_dispatch: permissions: @@ -22,6 +22,25 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + nightly-source-contract: + name: Nightly source contracts (no build or signing) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Run the synthetic nightly packaging suites + run: python3 packaging/nightly-tests.py + - name: Check the committed nightly icons still match their provenance + run: python3 packaging/nightly-icons.py --check + windows-install-policy: timeout-minutes: 10 name: Windows installation policy (no app build) diff --git a/.gitignore b/.gitignore index ab3202793a..f283435092 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,9 @@ plan/ /.claude/ /target-*/ /craft-fonts/ + +# Checked out inside the workspace by the shared nightly workflows (craft-common-actions). +/.nightly-tools +/.nightly-input +/craft-i18n +__pycache__/ diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index d63b32f16c..297e07ba09 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -38,6 +38,12 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render | | `assets/app-icon/hicolor/512x512/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, copy of gridcraft.svg | +| `assets/app-icon/gridcraft-nightly.svg` | GridCraft contributors | original (the stable placeholder artwork with only its field colour deepened; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly (nightly-v1) icon master | +| `assets/app-icon/gridcraft-nightly.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, 256 px (Linux tar and runtime window icon) | +| `assets/app-icon/gridcraft-nightly-1024.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg` on the 824/1024 Mac grid; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, padded Mac master | +| `assets/app-icon/gridcraft-nightly.icns` | GridCraft contributors | original (PNG slots packed from `gridcraft-nightly.svg` renders; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS bundle icon | +| `assets/app-icon/gridcraft-nightly.ico` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows exe icon | +| `assets/app-icon/nightly-provenance.json` | GridCraft contributors | original (written by `packaging/nightly-icons.py`) | MIT OR Apache-2.0 | Hashes and method of the nightly icon derivatives | | `assets/app-icon/README.md` | GridCraft contributors | original | MIT OR Apache-2.0 | Icon documentation | | `assets/app-icon/LICENSE.txt` | (licence text) | original | — | Licence of the app icon files | | `docs/images/hero-sales.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | diff --git a/Cargo.lock b/Cargo.lock index 2903e7010c..5a20a5b76a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2291,6 +2291,7 @@ dependencies = [ "serde_json", "winit", "winresource", + "winsafe", ] [[package]] diff --git a/README.md b/README.md index a58f4fb195..9e624bc01c 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,10 @@ directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a t matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings) log to standard error only. +The `nightly-v1` channel keeps all of that in its own profile instead, which the Launcher names +(`--launch-profile nightly-v1 --profile-root `); a nightly build refuses to start without one, +so a Nightly run never touches the stable app's settings, prefs or logs. + ## For agents: MCP, CLI and the control channel ```sh diff --git a/apps/gridcraft-cli/src/main.rs b/apps/gridcraft-cli/src/main.rs index 2c49c60334..d049757270 100644 --- a/apps/gridcraft-cli/src/main.rs +++ b/apps/gridcraft-cli/src/main.rs @@ -65,12 +65,35 @@ fn stdout_failed(e: std::io::Error) -> ! { std::process::exit(1); } +/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the +/// tokens a shell would see before `--` count: after it they are file names. +fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option { + for arg in args { + if arg == "--" { + return None; + } + let text = arg.to_string_lossy(); + for flag in ["--launch-profile", "--profile-root"] { + if text == flag || text.starts_with(&format!("{flag}=")) { + return Some(flag.to_string()); + } + } + } + None +} + fn main() -> ExitCode { // A confined launcher run (and its probes) comes first, before anything else starts. let raw: Vec = std::env::args_os().skip(1).collect(); if let Some(code) = gridcraft_sandbox::handle_args(&raw) { return ExitCode::from(u8::try_from(code).unwrap_or(1)); } + // The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a + // CLI option, and a CLI that silently ignored it would act on the wrong files. + if let Some(flag) = launch_profile_argument(&raw) { + eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI"); + return ExitCode::from(2); + } let args: Vec = std::env::args().skip(1).collect(); let rest = args.get(1..).unwrap_or_default(); let r = match args.first().map(String::as_str) { @@ -590,6 +613,22 @@ mod tests { #![allow(clippy::unwrap_used)] use super::*; + /// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2 + /// rather than acting on whatever it thinks the file list is. + #[test] + fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() { + let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::>(); + assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile")); + assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root")); + assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root")); + assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile")); + // After `--` they are file names, exactly as the desktop app parses them. + assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None); + assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None); + assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None); + assert_eq!(launch_profile_argument(&[]), None); + } + #[test] fn parses_commands() { assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"})))); diff --git a/apps/gridcraft/Cargo.toml b/apps/gridcraft/Cargo.toml index 572e89fa06..c94f12b29d 100644 --- a/apps/gridcraft/Cargo.toml +++ b/apps/gridcraft/Cargo.toml @@ -46,6 +46,8 @@ arboard = { workspace = true, features = ["image-data", "wayland-data-control"] [target.'cfg(target_os = "windows")'.dependencies] # Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe. pollster = "1" +# The explicit AppUserModelID the nightly channel sets before its first window (`process_identity.rs`). +winsafe = { version = "0.0.29", features = ["user", "shell"] } [target.'cfg(target_os = "macos")'.dependencies] muda = { version = "0.21", default-features = false } diff --git a/apps/gridcraft/build.rs b/apps/gridcraft/build.rs index 95d8da38d9..5d3b8a6a58 100644 --- a/apps/gridcraft/build.rs +++ b/apps/gridcraft/build.rs @@ -1,25 +1,67 @@ //! Windows only: embed the app icon and version info (VERSIONINFO) into `gridcraft.exe`, so it //! shows in Explorer, the taskbar, the Start menu and Alt-Tab. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a -//! cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! On every other target this does nothing but the channel work. A missing resource compiler is a +//! warning, so a cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` +//! turns it into an error (for release builds). +//! +//! The nightly channel is a build-time decision: `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` sets +//! `cfg(gridcraft_nightly_v1)` and requires the prepared `GRIDCRAFT_VERSION` feed identity, which +//! becomes the executable's `ProductVersion` (the Launcher checks that, not `FileVersion`) and the +//! version the app answers `--version` with. Anything else than `stable`, empty or `nightly-v1` +//! is a build error, so a typo cannot silently ship the wrong channel. + +#[path = "src/build_channel.rs"] +mod build_channel; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=GRIDCRAFT_BUILD_CHANNEL"); + println!("cargo:rustc-check-cfg=cfg(gridcraft_nightly_v1)"); + let nightly = match std::env::var("GRIDCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=gridcraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported GRIDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft-nightly.ico"); println!("cargo:rerun-if-env-changed=GRIDCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=GRIDCRAFT_VERSION"); + let built_version = if nightly { + match std::env::var("GRIDCRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit GRIDCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=GRIDCRAFT_BUILT_VERSION={built_version}"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/gridcraft.ico") - .set("ProductName", "GridCraft") - .set("FileDescription", "GridCraft spreadsheet") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "GridCraft Nightly" } else { "GridCraft" }) + .set("FileDescription", if nightly { "GridCraft Nightly spreadsheet" } else { "GridCraft spreadsheet" }) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the GridCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "gridcraft.exe") .set("InternalName", "gridcraft"); + if nightly { + // The Launcher compares the PE ProductVersion with the exact feed identity. + res.set("ProductVersion", &built_version); + } if let Err(e) = res.compile() { if std::env::var_os("GRIDCRAFT_REQUIRE_WINRES").is_some() { eprintln!("embedding Windows resources failed: {e}"); diff --git a/apps/gridcraft/src/app_dirs.rs b/apps/gridcraft/src/app_dirs.rs new file mode 100644 index 0000000000..241f0ccab6 --- /dev/null +++ b/apps/gridcraft/src/app_dirs.rs @@ -0,0 +1,92 @@ +//! The one place a GridCraft data root is resolved, so the nightly profile and the platform +//! default can never disagree. +//! +//! Everything the desktop writes about the user lives under [`config_dir`]: `ui.json`, +//! `prefs.json` and `logs/` (see `logging`). The control channel's token folder is resolved by +//! `gridcraft_mcp` from the same root at start-up. Nothing else in the app persists user state. +//! A nightly takes its root from the Launcher's validated profile and nothing else, so stable has +//! no environment override of its own: the platform's published folder is the whole story. + +use std::ffi::OsString; +use std::path::PathBuf; + +fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option) -> Option { + match platform { + "macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")), + "windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")), + _ => env("XDG_CONFIG_HOME") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))) + .map(|c| c.join("gridcraft")), + } +} + +/// The folder the settings and the log files live in. +pub fn config_dir_for(platform: &str, env: &impl Fn(&str) -> Option, nightly_root: Option<&std::path::Path>) -> Option { + match nightly_root { + // The profile was already validated (absolute, fenced, writable) before this runs. + Some(root) => Some(root.to_path_buf()), + None => default_config_dir(platform, env), + } +} + +pub fn config_dir() -> Option { + config_dir_for(std::env::consts::OS, &|key| std::env::var_os(key), crate::launch_profile::current().root()) +} + +/// Where the log files live: `logs` in the settings folder, next to `ui.json`. +pub fn log_dir() -> Option { + Some(config_dir()?.join("logs")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: BTreeMap = pairs.iter().map(|(k, v)| ((*k).to_string(), OsString::from(v))).collect(); + move |key| map.get(key).cloned() + } + + #[test] + fn each_platform_keeps_its_published_folder() { + // The base is joined with the host's own separator, so these hold on any machine the gate + // runs on: what each platform publishes is the folder name, not how the host spells a slash. + let appdata = PathBuf::from(r"C:\Users\u\AppData\Roaming"); + assert_eq!(config_dir_for("windows", &env(&[("APPDATA", &appdata.to_string_lossy())]), None), Some(appdata.join("GridCraft"))); + let home = PathBuf::from("/home/u"); + assert_eq!( + config_dir_for("macos", &env(&[("HOME", &home.to_string_lossy())]), None), + Some(home.join("Library/Application Support/GridCraft")) + ); + assert_eq!(config_dir_for("linux", &env(&[("HOME", &home.to_string_lossy())]), None), Some(home.join(".config").join("gridcraft"))); + assert_eq!( + config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home.to_string_lossy())]), None), + Some(PathBuf::from("/xdg").join("gridcraft")) + ); + assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "")]), None), None); + } + + #[test] + fn an_empty_xdg_config_home_falls_back_to_the_home_folder() { + let home = PathBuf::from("/home/u"); + let home_str = home.to_string_lossy().into_owned(); + assert_eq!( + config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", ""), ("HOME", &home_str)]), None), + Some(home.join(".config").join("gridcraft")) + ); + assert_eq!( + config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home_str)]), None), + Some(PathBuf::from("/xdg").join("gridcraft")) + ); + } + + #[test] + fn the_nightly_profile_is_the_whole_answer() { + let profile = std::path::Path::new("/var/lib/gridcraft-nightly/profile"); + assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", "/home/u")]), Some(profile)), Some(profile.to_path_buf())); + assert_eq!(config_dir_for("linux", &env(&[("HOME", "/home/u")]), Some(profile)).unwrap().join("logs"), profile.join("logs")); + } +} diff --git a/apps/gridcraft/src/build_channel.rs b/apps/gridcraft/src/build_channel.rs new file mode 100644 index 0000000000..322f540eec --- /dev/null +++ b/apps/gridcraft/src/build_channel.rs @@ -0,0 +1,55 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/gridcraft-nightly.ico" } else { "../../assets/app-icon/gridcraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/gridcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/gridcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.19.1-nightly.20261124.7.1.gabcdef012345")); + for invalid in [ + "", + "0.19.1", + "0.19.1-nightly", + "0.19.1-nightly.20261124", + "0.19.1-nightly.20261124.7.1.gABCDEF012345", + "0.19.1-nightly.20261124.7.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.19.1-nightly.20261124.1.1.gabcdef012345", + "0.19.1-nightly.20261124.1.1.gabcdef012345/other", + "0.19.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/gridcraft/src/build_flavor.rs b/apps/gridcraft/src/build_flavor.rs new file mode 100644 index 0000000000..485bd3bc6d --- /dev/null +++ b/apps/gridcraft/src/build_flavor.rs @@ -0,0 +1,73 @@ +//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a +//! stable build, and a nightly build cannot be talked out of its profile. +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open GridCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +pub fn version(flavor: BuildFlavor, stable: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.19.1"), "0.19.1 (nightly-v1)"); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/gridcraft/src/launch_profile.rs b/apps/gridcraft/src/launch_profile.rs new file mode 100644 index 0000000000..a25e5077b4 --- /dev/null +++ b/apps/gridcraft/src/launch_profile.rs @@ -0,0 +1,223 @@ +//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. +//! Stable launches keep their original arguments and directory policy. No environment mutation. +//! +//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with +//! `--profile-root ` as separate tokens, then `--` and the files. Everything after `--` +//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's +//! `--launch-profile nightly-v1 --profile-root --version`) is answered by `main` before any +//! of this can create a directory, open a log or start a window. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook +/// runs here. +pub fn parse(args: Vec) -> Result { + let mut selector = None; + let mut root = None; + let mut other = Vec::new(); + let mut files = Vec::new(); + let mut iter = args.iter(); + let mut delimiter = false; + while let Some(arg) = iter.next() { + if arg == "--" { + delimiter = true; + files.extend(iter.cloned()); + break; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err("the profile selector and root must each occur exactly once".into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; + if value.to_string_lossy().starts_with("--") { + return Err("the profile selector/root needs a value".into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); + } + let root = PathBuf::from(root); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err("the nightly profile root must be absolute and contain no parent traversal".into()); + } + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), + _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old config resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "/one/../two", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + ] { + assert!(parse(argv.clone()).is_err(), "{argv:?}"); + } + assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value"); + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "7979", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 858c7f9d1d..a05c11d9b0 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -9,16 +9,25 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod app_dirs; #[cfg(target_os = "macos")] mod apple_events; +// The build channel's own parser and icon-path tests (build.rs compiles the same file by path). +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; #[cfg(any(target_os = "windows", target_os = "macos", test))] mod graphics; +mod launch_profile; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod nightly_session; mod opener; mod print; +mod process_identity; +mod profile_root; use std::cell::RefCell; use std::rc::Rc; @@ -29,45 +38,63 @@ use gridcraft_ui_egui::{Services, SheetApp}; use serde_json::json; /// The app, its native window per workbook window, and (macOS) the menu bar and Finder events. -struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option, #[cfg(target_os = "macos")] fmv_macos_events::Inbox); +/// The session record and its notice flag are only meaningful in the nightly channel. +struct App { + app: SheetApp, + windows: DocWindows, + #[cfg(target_os = "macos")] + menu: Option, + #[cfg(target_os = "macos")] + apple_events: fmv_macos_events::Inbox, + /// The Nightly session record, shared with the exit hook and the return path. + nightly: nightly_session::Shared, + /// Whether this window already told the user the previous session did not finish. + nightly_notice_shown: bool, +} impl eframe::App for App { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] { - if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() { - self.2 = Some(native_menu::NativeMenu::install(ctx)); + if self.menu.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() { + self.menu = Some(native_menu::NativeMenu::install(ctx)); } - if let Some(m) = &mut self.2 { - m.poll(&mut self.0, ctx, self.1.focused_viewport()); + if let Some(m) = &mut self.menu { + m.poll(&mut self.app, ctx, self.windows.focused_viewport()); } - apple_events::poll(&self.3, &mut self.0, ctx); + apple_events::poll(&self.apple_events, &mut self.app, ctx); } - self.0.logic(ctx); - self.1.logic(&mut self.0, ctx); - if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() { + self.app.logic(ctx); + self.windows.logic(&mut self.app, ctx); + if ctx.input(|input| input.viewport().close_requested()) && self.app.printing.busy() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); } } /// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - self.0.raw_input_hook(ctx, raw); + self.app.raw_input_hook(ctx, raw); // Files dropped on the window open as workbooks. for f in std::mem::take(&mut raw.dropped_files) { if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) { - self.0.open_path(&p); + self.app.open_path(&p); } } } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { - self.1.show(&mut self.0, ui); + self.windows.show(&mut self.app, ui); } fn on_exit(&mut self) { print::finish_pending_jobs(); - save_prefs(&self.0); + save_prefs(&self.app); // A ready update installs once the process has exited. The macOS exit below skips - // dropping the app, so the helper is started here. - self.0.start_pending_update(); + // dropping the app, so the helper is started here. A nightly has no updater at all. + if gridcraft_ui_egui::channel::stable_services_allowed() { + self.app.start_pending_update(); + } + // The Nightly session record is finished here: every way of quitting reaches `on_exit`, + // and on macOS AppKit's terminate ends the process right after it, so nothing after + // `eframe::run_native` can run there. `finish_once` makes the later call a no-op. + nightly_session::finish_once(&self.nightly, self.nightly_notice_shown); // macOS (#117): end the process here, before eframe tears the window down. AccessKit's // macOS adapter subclasses the window's content view and restores its class on teardown; // AppKit's Touch Bar support observes that view (KVO), so in the next display cycle @@ -81,17 +108,10 @@ impl eframe::App for App { } } +/// The settings folder: the validated nightly profile, else the platform's own folder +/// (`app_dirs`). Every writer of user state goes through it. fn config_dir() -> Option { - if cfg!(target_os = "macos") { - std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/GridCraft")) - } else if cfg!(windows) { - std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("GridCraft")) - } else { - std::env::var_os("XDG_CONFIG_HOME") - .map(std::path::PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config"))) - .map(|c| c.join("gridcraft")) - } + app_dirs::config_dir() } /// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write @@ -102,7 +122,7 @@ fn prefs_enabled() -> bool { /// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`). fn log_dir() -> Option { - Some(config_dir()?.join("logs")) + app_dirs::log_dir() } fn load_prefs(app: &mut SheetApp) { @@ -241,13 +261,97 @@ fn icon() -> Option { Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() }) } +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize( + build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, + gridcraft_ui_egui::channel::id_for(gridcraft_ui_egui::channel::Channel::NightlyV1), + ) +} + +/// Tell a desktop user why a nightly launch was refused. A headless form (`--version` on a runner) +/// never gets here: the version query is answered before this and before any profile work. +fn report_launch_profile_error(error: &str) { + eprintln!("GridCraft launch profile: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("GridCraft launch profile: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title("GridCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch channel and profile before any startup service or side effect. +/// `None` means the answer was printed (`--version`) and the process is done. +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1; + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: answered before root validation, process identity, IPC or any window (a dialog + // here would hang a headless runner and fail a Linux build). + if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION")); + let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable)); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| { + launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) + }) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let channel = + if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable }; + if let Err(error) = + launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION"))) + { + report_launch_profile_error(&error); + std::process::exit(2); + } + Some(early.args) +} + fn main() -> eframe::Result<()> { - // A confined launcher run (`gridcraft_sandbox::launch_command`) comes before everything else: - // it opens no window, writes no log, and becomes the program it confines. + // A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from + // this same executable) comes before everything else: it opens no window, writes no log, and + // becomes the program it confines. It must stay ahead of the launch profile, or a nightly build + // would refuse its own sandbox helper. let raw: Vec = std::env::args_os().skip(1).collect(); if let Some(code) = gridcraft_sandbox::handle_args(&raw) { std::process::exit(code); } + // Then the Launcher protocol and the version query (see `prepare_launch`). + let Some(arguments) = prepare_launch() else { return Ok(()) }; + // A nightly profile owns its control tokens as well, so even a nightly build that is asked + // for a control server can never write the stable app's token file. + if let Some(root) = launch_profile::current().root() { + match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) { + Ok(()) => {} + Err(error) => { + report_launch_profile_error(&error); + std::process::exit(2); + } + } + } // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); // Commands catch their panics (`Session::execute`), but the default hook only prints to @@ -268,21 +372,32 @@ fn main() -> eframe::Result<()> { let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n")); } })); - let args: Vec = std::env::args().skip(1).collect(); + let args: Vec = arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect(); + let nightly = gridcraft_ui_egui::channel::current() == gridcraft_ui_egui::channel::Channel::NightlyV1; // The restart helper a self-update spawns: it finishes the swap and relaunches, then exits. - if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + // A nightly has no updater, so it never runs this and never inherits a stable swap. + if !nightly + && let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { if let Err(e) = done { eprintln!("GridCraft update helper failed: {e}"); std::process::exit(1); } return Ok(()); } - if args.iter().any(|a| a == "--version" || a == "-V") { - println!("GridCraft {}", env!("CARGO_PKG_VERSION")); + // Before `--` only: everything after it is a file, even one named `--version`. + if arguments.iter().take_while(|a| *a != "--").any(|a| a == "--version" || a == "-V") { + println!("GridCraft {}", gridcraft_ui_egui::channel::version()); return Ok(()); } - let mut control_port: Option = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()); - let mut control_token: Option = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok(); + // The control channel is a stable-only service: a nightly window owns no port, writes no + // token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`. + if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") { + eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel"); + std::process::exit(2); + } + let mut control_port: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten(); + let mut control_token: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten(); let mut sample: Option = None; let mut files: Vec = Vec::new(); let mut i = 0; @@ -312,7 +427,9 @@ fn main() -> eframe::Result<()> { if let Some(logger) = logger { match log_dir().filter(|_| prefs_enabled()) { Some(dir) => match logger.attach_dir(&dir) { - Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()), + Ok(path) => { + log::info!("{} {}, log file {}", gridcraft_ui_egui::channel::name(), gridcraft_ui_egui::channel::version(), path.display()) + } // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. Err(e) => log::warn!("no log file: {e}"), }, @@ -327,7 +444,11 @@ fn main() -> eframe::Result<()> { } let mut app = SheetApp::new(session, services()); app.watch_desktop_theme(); - app.start_update_check(); + // The updater is a stable-only service: a nightly is installed, replaced and updated by the + // Launcher, so it never checks for one, never prompts and never writes craft-update's state. + if !nightly { + app.start_update_check(); + } let control_port = control_port; load_prefs(&mut app); // Stamp the startup workbook's author from the persisted user name. @@ -335,6 +456,30 @@ fn main() -> eframe::Result<()> { app.session.new_workbook(); } app.after_engine(); // Show warnings from the sample. + // Nightly session health: the record is written before the window exists and finished by + // `on_exit`. A record left by an interrupted run is reported once, then cleared on the next + // clean quit. + let session_watch = std::sync::Arc::new(std::sync::Mutex::new(None)); + let mut nightly_notice_shown = false; + match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("GRIDCRAFT_BUILT_VERSION")) { + Ok((watch, unavailable)) => { + if let Some(watch) = &watch + && watch.previous_unclean() + { + app.notice = Some(gridcraft_ui_egui::Notice { + text: "The last GridCraft Nightly session did not finish cleanly. Your saved workbooks are as you left them; only unsaved changes are affected.".into(), + kind: gridcraft_ui_egui::NoticeKind::Warning, + action: None, + }); + nightly_notice_shown = true; + } + if unavailable { + log::warn!("this window shares a GridCraft Nightly profile another window owns; its exit is not recorded"); + } + *session_watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = watch; + } + Err(error) => log::warn!("Nightly session state was not written: {error}"), + } // Files named on the command line (a double-click on Windows and Linux) open as File › Open // opens them: a password-protected one asks for its password, and errors are shown, not // only logged. Each replaces the untouched blank Book1, as a file opened from Finder does. @@ -344,11 +489,16 @@ fn main() -> eframe::Result<()> { // Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the // window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame. app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none(); + // The window carries its channel's name and OS app id: a nightly window is never mistaken for + // the stable one by a dock, a window manager rule or the taskbar (Windows AUMID above). A + // Flatpak package carries its own id instead, which is what its .desktop file and portal name. + let window_app_id = + std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| gridcraft_ui_egui::channel::app_id().to_string()); let mut viewport = egui::ViewportBuilder::default() - .with_title("GridCraft") + .with_title(gridcraft_ui_egui::channel::default_title()) .with_inner_size([1440.0, 900.0]) .with_min_inner_size([640.0, 420.0]) - .with_app_id("ai.storyteller.gridcraft") + .with_app_id(window_app_id) .with_drag_and_drop(true) .with_decorations(!app.window_controls); if cfg!(target_os = "macos") { @@ -387,7 +537,7 @@ fn main() -> eframe::Result<()> { let pending = std::cell::Cell::new(Some(app)); let run = |options: eframe::NativeOptions| { eframe::run_native( - "GridCraft", + gridcraft_ui_egui::channel::name(), options, Box::new(|cc| { let Some(mut app) = pending.take() else { @@ -401,14 +551,16 @@ fn main() -> eframe::Result<()> { } } let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window()); - Ok(Box::new(App( + Ok(Box::new(App { app, windows, #[cfg(target_os = "macos")] - None, + menu: None, #[cfg(target_os = "macos")] - apple_events.connect(&cc.egui_ctx), - ))) + apple_events: apple_events.connect(&cc.egui_ctx), + nightly: session_watch.clone(), + nightly_notice_shown, + })) }), ) }; @@ -416,7 +568,7 @@ fn main() -> eframe::Result<()> { // A graphics error before the app existed: start once more with the other backend (eframe // reuses its event loop for the second run). Errors after that, or from winit, are returned. #[cfg(target_os = "windows")] - if let Err(eframe::Error::Wgpu(e)) = &result + let result = if let Err(eframe::Error::Wgpu(e)) = &result && let Some(app) = pending.take() && let Some(backends) = graphics::fallback_backends(backend_override, first_backends) { @@ -424,8 +576,14 @@ fn main() -> eframe::Result<()> { pending.set(Some(app)); let mut options = retry_options; graphics::configure_backends(&mut options, backends); - return run(options); - } + run(options) + } else { + result + }; + // A start that failed before the app existed never reached `on_exit`, and on the platforms + // where the event loop returns this is also the end of a clean exit. `finish_once` makes the + // second of the two calls a no-op, so a successor's record is never touched. + nightly_session::finish_once(&session_watch, nightly_notice_shown); result } diff --git a/apps/gridcraft/src/nightly_session.rs b/apps/gridcraft/src/nightly_session.rs new file mode 100644 index 0000000000..597bb4b2a8 --- /dev/null +++ b/apps/gridcraft/src/nightly_session.rs @@ -0,0 +1,310 @@ +//! App-private Nightly session health, not telemetry and not a Launcher protocol. +//! +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker: only the app's controlled return path does, and +//! on macOS that path is `on_exit` (a ⌘Q ends the process inside AppKit's terminate, after +//! `on_exit`, so nothing after `eframe::run_native` runs there). + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Replace `path` with `bytes` without following a link at the destination: the temporary file is +/// created exclusively beside it and renamed over it, so a planted link is replaced, not written +/// through. `gridcraft_engine::io::write_file` does the same for workbooks; the session record is +/// the app's own file and must not depend on the engine's script sandbox policy. +fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no file name"))?; + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(".new"); + let tmp = path.with_file_name(tmp_name); + match std::fs::remove_file(&tmp) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let write = (|| -> io::Result<()> { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let mut file = options.open(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&tmp, path) + })(); + if write.is_err() { + let _ = std::fs::remove_file(&tmp); + } + write +} + +/// The owner's session, shared by the app's exit hook and the return path. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, while + /// Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is stable, or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + // The commit is read back from the version (`…g`), never invented here. + let commit = gridcraft_ui_egui::channel::commit_for(version); + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit, + }))?; + atomic_write_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed it + /// yet (a failed start before the app existed), the record is left for the next owner. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// Clear the record this owner wrote, and only that one. An unwind, abort, forced exit or killed + /// process never calls this. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = + std::env::temp_dir().join(format!("gridcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + fn version() -> &'static str { + "0.19.1-nightly.20261124.7.1.gabcdef012345" + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable").unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), version()).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), version()).unwrap().unwrap()); + // The renderer failed before the app existed: no notice was shown. + let failed = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The retry (or the next start) still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), version()).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + let successor = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1)).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "").unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["channel", "commit", "schema_version", "version"].into_iter().collect()); + assert_eq!(data["commit"], "abcdef012345", "the commit comes from the version, not the environment"); + watch.complete().unwrap(); + } + + #[test] + fn a_version_without_a_commit_does_not_invent_one() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "0.19.1").unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + assert!(data["commit"].is_null()); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), version()).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } + + #[test] + #[cfg(unix)] + fn replacing_a_planted_record_link_writes_our_own_file_only() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap(); + // regular_or_missing refuses an alias outright; the temporary writer is what a first write + // uses, and it never follows one either. + assert!(Session::begin(Some(&fixture.0), version()).is_err()); + // The link is at RECORD itself: writing there must replace the alias, not follow it. + atomic_write_no_follow(&fixture.0.join(RECORD), b"ours").unwrap(); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"ours"); + assert!(!fixture.0.join(RECORD).is_symlink(), "the alias must be replaced, not written through"); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + assert!(!fixture.0.join(".nightly-session.json.new").exists()); + } +} diff --git a/apps/gridcraft/src/process_identity.rs b/apps/gridcraft/src/process_identity.rs new file mode 100644 index 0000000000..23ce47653c --- /dev/null +++ b/apps/gridcraft/src/process_identity.rs @@ -0,0 +1,81 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so the MSI's +//! advertised shortcuts keep matching it. + +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityError(String); + +impl std::fmt::Display for IdentityError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IdentityError {} + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } + + #[test] + fn a_non_nightly_build_never_reaches_the_windows_api() { + assert!(initialize(false, "nightly-id").is_ok()); + } +} diff --git a/apps/gridcraft/src/profile_root.rs b/apps/gridcraft/src/profile_root.rs new file mode 100644 index 0000000000..d911a3fa46 --- /dev/null +++ b/apps/gridcraft/src/profile_root.rs @@ -0,0 +1,528 @@ +//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the +//! process environment. Every stable place a GridCraft build keeps user state is refused as a +//! nightly root, in both directions, so the two channels can never share a file. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`). +const WINDOWS_TOKEN_DIR: &str = ".gridcraft"; +/// The subfolder of the profile the nightly control-channel token goes to, when one runs. +pub const CONTROL_DIR: &str = "Control"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + // FreeBSD, the BSDs and anything else have no nightly channel. + _ => Err("nightly-v1 is not defined for this operating system".into()), + } + } + + fn ignores_case(self) -> bool { + self != Self::Linux + } +} + +fn absolute(path: PathBuf, label: &str) -> Result { + if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{label} must be absolute and contain no parent traversal")); + } + Ok(path) +} + +fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { + let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; + absolute(PathBuf::from(value), key) +} + +fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible +/// ancestor is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + let mut parent = path; + let mut missing = Vec::new(); + loop { + match std::fs::symlink_metadata(parent) { + Ok(_) => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); + parent = parent.parent().ok_or("the profile root has no existing ancestor")?; + } + Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), + } + } + let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; + for part in missing.into_iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { + let parts = |p: &Path| { + p.components() + .map(|c| { + let value = c.as_os_str().to_string_lossy().into_owned(); + if platform.ignores_case() { value.to_lowercase() } else { value } + }) + .collect::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or("cannot establish the installation boundary")?; + if platform == Platform::Mac { + // A profile in Resources is still inside the versioned install, not beside MacOS. + if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { + return Ok(bundle.to_path_buf()); + } + } + Ok(parent.to_path_buf()) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + // `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s + // token folder, plus both MSI install folders (`install-policy.wxi`). + let mut roots = ["APPDATA", "LOCALAPPDATA"] + .into_iter() + .map(|key| required_base(env, key).map(|p| p.join("GridCraft"))) + .collect::, _>>()?; + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft")); + roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR)); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = env(key).filter(|v| !v.is_empty()) { + roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("GridCraft")); + } + } + roots + } + Platform::Linux => { + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from)); + // The stable Flatpak keeps its data in its own per-app folder. + roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft")); + // `gridcraft_mcp`'s token folder when no XDG runtime directory is set. + roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/GridCraft"), + library.join("Caches/GridCraft"), + library.join("Caches/ai.storyteller.gridcraft"), + library.join("Preferences/GridCraft"), + library.join("Preferences/ai.storyteller.gridcraft.plist"), + library.join("Saved Application State/ai.storyteller.gridcraft.savedState"), + home.join("Applications/GridCraft.app"), + PathBuf::from("/Applications/GridCraft.app"), + ] + } + }; + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(format!("the nightly {label} must stay inside its selected profile")); + } + Ok(child) +} + +/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it, +/// so a link there cannot point Nightly's writes at the stable app's data. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let entries = match std::fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), + }; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + Ok(()) +} + +/// Where a nightly control-channel token goes: `/Control`, created lazily by +/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything. +pub fn control_directory(root: &Path) -> Result { + private_subdirectory(root, CONTROL_DIR, "control folder") +} + +/// The app's own exclusive writable probe: create a file inside the profile, then remove it. +pub fn ensure_writable(root: &Path) -> std::io::Result<()> { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + // A crashed launch can leave a probe with this name behind: take the next one instead of + // failing, and remove only the file this call created, never someone else's. + loop { + let probe = + root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(_) => return std::fs::remove_file(&probe), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } +} + +/// The writable hook is injected so filesystem boundary tests exercise the real policy without +/// starting the app or changing global state. +pub fn validate( + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + absolute(root.to_path_buf(), "the nightly profile root")?; + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty()) + && id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID + { + // `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak + // (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one + // instance may carry a profile. Any other, the stable app's included, could point it at + // another installation's tree; these rows are otherwise native tar/app-bundle launches. + return Err(format!( + "nightly-v1 can only run inside its own Flatpak instance ({}), not {}", + gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, + id.to_string_lossy() + )); + } + let chosen = canonical_future(root)?; + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + // Existing aliases under the profile must not redirect a subfolder elsewhere. + control_directory(&chosen)?; + entries_stay_inside(&chosen)?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + control_directory(&confirmed)?; + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/gridcraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + self.check_with(platform, root, |_| Ok(())) + } + + fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result { + validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory successfully created by this fixture is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn every_stable_data_root_is_refused_on_its_own_platform() { + let mut fixture = Fixture::new(); + // Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user + // and per-machine install folders and the control-token folder. + for key in ["APPDATA", "LOCALAPPDATA"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft"); + for candidate in [stable.clone(), stable.join("nightly")] { + assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}"); + } + assert!(!stable.exists()); + } + assert!( + fixture + .check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly")) + .is_err() + ); + assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err()); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + let base = fixture.root.join(format!("machine {key}")); + fixture.env.insert(key.into(), base.clone().into_os_string()); + assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}"); + assert!(!base.join("ArtCraft/GridCraft").exists()); + } + // Linux: the four XDG folders, then the stable Flatpak row and the token folder. + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + fixture.env.insert(key.into(), fixture.root.join(key).into_os_string()); + } + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); + for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}"); + } + assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); + } + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err()); + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); + assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused"); + // macOS: the four Library rows and the bundle itself. + for suffix in [ + "Application Support/GridCraft", + "Caches/GridCraft", + "Preferences/GridCraft", + "Saved Application State/ai.storyteller.gridcraft.savedState", + ] { + assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}"); + } + } + + #[test] + fn the_launcher_profile_row_is_accepted_on_every_platform() { + let fixture = Fixture::new(); + let data = fixture.root.join("Launcher/nightly/profiles/gridcraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert_eq!(fixture.check(platform, &data).unwrap(), data); + } + assert!( + fixture + .check( + Platform::Linux, + &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft") + ) + .is_ok(), + "the Launcher's own folder is not GridCraft's install" + ); + } + + #[test] + fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/gridcraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(overlaps(&root, &root.join("Control"), platform)); + assert!(overlaps(&root.join("Control"), &root, platform)); + assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform)); + } + } + + #[test] + fn the_install_folder_of_the_running_build_is_refused() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err()); + } + } + + #[test] + fn mac_fences_the_whole_bundle_not_just_its_macos_folder() { + let mut fixture = Fixture::new(); + fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft"); + std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); + std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); + let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile"); + assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap")); + assert!(!inside_resources.exists()); + assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok()); + } + + #[test] + fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { + let mut fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/gridcraft"); + fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); + fixture.env.remove("XDG_CACHE_HOME"); + fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + fixture.env.remove("FLATPAK_ID"); + fixture.env.remove("HOME"); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); + assert!(!candidate.exists()); + } + + #[test] + fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() { + let mut fixture = Fixture::new(); + let root = fixture.root.join("flatpak profile"); + for (id, accepted) in [ + (gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true), + // The stable Flatpak, and a lookalike that only shares the prefix, stay refused. + ("ai.storyteller.gridcraft", false), + ("ai.storyteller.gridcraft.nightly-v1", false), + ("io.github.other.Gridcraft", false), + ] { + fixture.env.insert("FLATPAK_ID".into(), id.into()); + let result = fixture.check(Platform::Linux, &root); + assert_eq!(result.is_ok(), accepted, "{id}"); + let _ = std::fs::remove_dir_all(&root); + } + } + + #[test] + fn failed_write_probe_never_falls_back_to_stable() { + let fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/gridcraft"); + let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount"))); + assert!(result.unwrap_err().contains("not writable")); + assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data"); + assert!(!fixture.home().join(".config/gridcraft").exists()); + } + + #[test] + fn a_file_in_place_of_the_profile_is_refused() { + let fixture = Fixture::new(); + let candidate = fixture.root.join("not-a-directory"); + std::fs::write(&candidate, b"a file, not a profile").unwrap(); + assert!(fixture.check(Platform::Linux, &candidate).is_err()); + assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile"); + } + + #[cfg(unix)] + #[test] + fn profile_entry_aliases_must_stay_inside_the_profile() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".config/gridcraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("ui.json"), b"stable settings").unwrap(); + for name in ["ui.json", "logs", "Control", "profile"] { + let private = fixture.root.join(format!("nightly-{name}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); + let probed = std::cell::Cell::new(false); + let result = fixture.check_with(Platform::Linux, &private, |_| { + probed.set(true); + Ok(()) + }); + assert!(result.is_err(), "{name} must not lead outside the profile"); + assert!(!probed.get()); + } + let private = fixture.root.join("nightly-inside"); + std::fs::create_dir_all(private.join("real-logs")).unwrap(); + std::fs::write(private.join("ui.json"), b"{}").unwrap(); + std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine"); + assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings"); + assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); + } + + #[cfg(unix)] + #[test] + fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() { + let fixture = Fixture::new(); + let outside = fixture.home().join("shared-tokens"); + std::fs::create_dir_all(&outside).unwrap(); + let private = fixture.root.join("nightly-control"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap(); + assert!(control_directory(&private).is_err()); + assert!(fixture.check(Platform::Linux, &private).is_err()); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + } + + #[test] + fn the_control_folder_is_a_private_lazy_subfolder() { + let fixture = Fixture::new(); + let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap(); + let control = control_directory(&private).unwrap(); + assert!(control.starts_with(&private) && control != private); + assert!(!control.exists(), "resolving it must not create it"); + assert_eq!(control.file_name().unwrap(), CONTROL_DIR); + } + + #[test] + fn the_writable_probe_leaves_nothing_behind() { + let fixture = Fixture::new(); + let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap(); + ensure_writable(&private).unwrap(); + assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 349dcfd5ab..b77585ff12 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -50,3 +50,16 @@ ID and `packaging/linux/ai.storyteller.gridcraft.desktop`. Edit `gridcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the `.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`. + +## Nightly channel + +The nightly (`nightly-v1`) derivatives keep the artwork, geometry and the Mac padding unchanged and +change only the field colour: `#1f9d55` in the stable icon, `#14532d` in +`gridcraft-nightly.svg`. There is no letter, badge or crescent; the app and the Launcher name the +channel in text (`GridCraft Nightly`, the `ai.storyteller.gridcraft.nightly-v1` window id). + +`gridcraft-nightly.svg` is the vector master. `packaging/nightly-icons.py` renders every frame from +it at its own size (never an upscale) and packs the nine-frame ICO and the eleven-slot ICNS; it +uses `resvg` when present, else a headless Chrome. Each output's SHA-256, the palette and the +method are recorded in [`nightly-provenance.json`](nightly-provenance.json), and +`python3 packaging/nightly-icons.py --check` verifies the committed files still match it. diff --git a/assets/app-icon/gridcraft-nightly-1024.png b/assets/app-icon/gridcraft-nightly-1024.png new file mode 100644 index 0000000000000000000000000000000000000000..7017cd5af97d80fa5cae561c20b181a51cc60837 GIT binary patch literal 61068 zcmeFZ`9IWO*av)O>`RCwNv5(CAxV;LMA<3(KC&;BvTtK16eW?JY>|Br*$t(H>^oV? zzOQ2)=J|~8eLt_~^?Lq=+b;&^b3W%>%lo>n_qmQY4>c4|(VnLT0Gv`*QqTf`9QsHO zs41au7*2rz0GNQXf}D{1Exi76KUkYSWy0raF4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GH(OK|56GNpjF}4H9sC@_3aHn`is2yKT!k!{{g$$ BlO6y7 literal 0 HcmV?d00001 diff --git a/assets/app-icon/gridcraft-nightly.svg b/assets/app-icon/gridcraft-nightly.svg new file mode 100644 index 0000000000..1966f77a7d --- /dev/null +++ b/assets/app-icon/gridcraft-nightly.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..d34aea93fb --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,56 @@ +{ + "title": "GridCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": [ + { + "path": "assets/app-icon/gridcraft-nightly.svg", + "sha256": "671748d45b785a840cf6ad062024c008e4704edc8925bed986dac2558438516b", + "purpose": "vector master for every frame" + }, + { + "path": "assets/app-icon/gridcraft.svg", + "sha256": "a4c55f2f52893b319862b610c006af83da9f097a4112b5a982b8ba95f43d2850", + "purpose": "stable artwork this is derived from" + } + ], + "method": { + "kind": "vector render of the project-owned artwork with only its field colour deepened", + "stable_field": "#1f9d55", + "nightly_field": "#14532d", + "unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding", + "sizes": "each frame rendered at its own size, never upscaled", + "renderer": "chrome", + "generator": "packaging/nightly-icons.py" + }, + "outputs": { + "gridcraft-nightly.png": "f06a2507dbd07c307d3b3e46eb2b7d849c29cc51f56114d61091d68d9d59e0d0", + "gridcraft-nightly-1024.png": "914314b91dd214132bc017503d88197ca1537fab0de144a59cc65e03a03be400", + "gridcraft-nightly.ico": "20cdb98a65c157f1db67800d439730b2c5dd564722d615d2b9483dc948f6e751", + "gridcraft-nightly.icns": "e8fb90269660151b8ab1370bbd7194f5bae29888aa44959cf4c48110dcdebe9a" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + } +} diff --git a/crates/mcp/src/control_auth.rs b/crates/mcp/src/control_auth.rs index 7ff589353d..b3fcabf582 100644 --- a/crates/mcp/src/control_auth.rs +++ b/crates/mcp/src/control_auth.rs @@ -68,10 +68,26 @@ pub fn check_first_line(line: &str, token: &str) -> Result { } } -/// Where the app writes the token it made for `port`, and where clients look for it: a folder -/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows -/// `%USERPROFILE%\.gridcraft`), file `control-.token`. `None` when no such folder is known. -pub fn token_path(port: u16) -> Option { +/// An app-selected folder for the tokens, set once before any window exists. The nightly channel +/// points it at its own private profile, so a nightly control server can never write the stable +/// app's token (and two channels can never authenticate each other). +static TOKEN_ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Choose the token folder for this process. Only a desktop app that owns its data root calls +/// this; a client (`gridcraft-cli`, the MCP bridge) keeps reading the app's own folder. +pub fn set_token_root(dir: PathBuf) -> Result<(), String> { + if !dir.is_absolute() { + return Err("the control token folder must be absolute".into()); + } + TOKEN_ROOT.set(dir).map_err(|_| "the control token folder was already selected".to_string()) +} + +/// The folder tokens go in: [`set_token_root`]'s when an app chose one, else the user's own. +pub fn token_root() -> Option { + TOKEN_ROOT.get().cloned().or_else(default_token_root) +} + +fn default_token_root() -> Option { let dir = if cfg!(windows) { PathBuf::from(std::env::var_os("USERPROFILE").filter(|v| !v.is_empty())?).join(".gridcraft") } else if let Some(run) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) { @@ -79,7 +95,14 @@ pub fn token_path(port: u16) -> Option { } else { PathBuf::from(std::env::var_os("HOME").filter(|v| !v.is_empty())?).join(".cache").join("gridcraft") }; - Some(dir.join(format!("control-{port}.token"))) + Some(dir) +} + +/// Where the app writes the token it made for `port`, and where clients look for it: a folder +/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows +/// `%USERPROFILE%\.gridcraft`), file `control-.token`. `None` when no such folder is known. +pub fn token_path(port: u16) -> Option { + Some(token_root()?.join(format!("control-{port}.token"))) } /// The port of a control address (`127.0.0.1:7979` → 7979). diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 3b1b71f066..9027fc5032 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -512,6 +512,15 @@ fn control_auth_handshake_and_compare() { assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff"); } +#[test] +fn a_relative_token_root_is_refused_before_it_is_selected() { + // The app may point the tokens at its own private profile, but only at an absolute folder: a + // relative one would resolve against whatever directory the process was started in. (A + // successful selection is process-wide, so this test only exercises the refusal.) + assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("relative/tokens")).is_err()); + assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("")).is_err()); +} + #[cfg(unix)] #[test] fn control_token_file_is_private() { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 471905fbde..8b9a59c488 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -164,6 +164,7 @@ impl SheetApp { } let Some(d) = self.session.active() else { return }; let title = format!("{}{}", d.display_title(), if d.is_dirty() { " — Edited" } else { "" }); + let title = crate::channel::window_title(&title); if self.grid.last_title.as_deref() != Some(title.as_str()) { ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone())); self.grid.last_title = Some(title); diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 151374e6e4..6c3f5bd87a 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -50,13 +50,22 @@ impl SheetApp { /// Look for a newer release once, in the background, as the desktop app starts (a no-op on the /// web). A found release opens the update prompt; nothing is shown when GridCraft is current. + /// A nightly channel has no update feed of its own: the Launcher installs and replaces it. pub fn start_update_check(&mut self) { #[cfg(not(target_arch = "wasm32"))] - updates_ui::start(self, false); + if crate::channel::stable_services_allowed() { + updates_ui::start(self, false); + } } /// Help ▸ Check for Updates…: look now, and say so when GridCraft is up to date or the check fails. pub fn check_for_updates(&mut self) { + // Never from the nightly channel: a check would download into, and record in, the stable + // app's folders, and an install would replace a Launcher-managed copy. + if !crate::channel::stable_services_allowed() { + self.message = Some((crate::channel::name().into(), "GridCraft Nightly is updated by ArtCraft Launcher.".into())); + return; + } #[cfg(not(target_arch = "wasm32"))] updates_ui::start(self, true); #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 194533d369..3b4afe6c4b 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -798,11 +798,11 @@ fn account(app: &mut SheetApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let lang = app.ui.language; section(ui, lang, "Product Information"); - ui.label(RichText::new("GridCraft").font(theme::ui_bold(16.0)).color(t.text)); + ui.label(RichText::new(crate::channel::name()).font(theme::ui_bold(16.0)).color(t.text)); ui.add_space(8.0); egui::Grid::new("backstage_account").num_columns(2).spacing(vec2(18.0, 8.0)).show(ui, |ui| { for (label, value) in - [("Version", env!("CARGO_PKG_VERSION").to_string()), ("Platform", platform()), ("Licence", env!("CARGO_PKG_LICENSE").to_string())] + [("Version", crate::channel::version().to_string()), ("Platform", platform()), ("Licence", env!("CARGO_PKG_LICENSE").to_string())] { ui.label(RichText::new(lang.tr(label)).color(t.text_dim)); ui.label(value); diff --git a/crates/ui-egui/src/channel.rs b/crates/ui-egui/src/channel.rs new file mode 100644 index 0000000000..4a19d72dff --- /dev/null +++ b/crates/ui-egui/src/channel.rs @@ -0,0 +1,167 @@ +//! The compiled channel this process belongs to: its OS identity, its window titles and the +//! version the Help ▸ About and File ▸ Account views show. +//! +//! The desktop selects it once, before any window exists (`prepare_launch`), so a launch cannot +//! change it later and nothing here is a user preference. A stable build keeps its old identity +//! and titles byte for byte; the nightly build carries its own app id so docks, window managers +//! and the taskbar keep the two channels apart. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU8, Ordering}; + +/// The stable window/Wayland app id, matching the `.desktop` file and the hicolor icon name. +pub const APP_ID: &str = "ai.storyteller.gridcraft"; +/// The nightly window id and Windows AUMID. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.gridcraft.nightly-v1"; +/// The nightly Flatpak package (and macOS bundle) identity, `packaging/linux/flatpak-bundle.sh`. +/// A different string from [`NIGHTLY_APP_ID`] on purpose: inside its sandbox the Flatpak names the +/// window after the package id, which is what its `.desktop` file and portal entry carry. +pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.gridcraft.nightly"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Channel { + Stable, + NightlyV1, +} + +static SELECTED: AtomicU8 = AtomicU8::new(0); +static VERSION: OnceLock<&'static str> = OnceLock::new(); + +/// Fix the channel and its version for this process, once. `version` is the build's own identity +/// (`GRIDCRAFT_BUILT_VERSION` from `build.rs`), not a value read from the environment at runtime. +pub fn select(channel: Channel, version: &'static str) -> Result<(), String> { + let value = match channel { + Channel::Stable => 1, + Channel::NightlyV1 => 2, + }; + SELECTED.compare_exchange(0, value, Ordering::AcqRel, Ordering::Acquire).map_err(|_| "the channel was already selected".to_string())?; + VERSION.set(version).map_err(|_| "the channel version was already selected".to_string()) +} + +pub fn current() -> Channel { + if SELECTED.load(Ordering::Acquire) == 2 { Channel::NightlyV1 } else { Channel::Stable } +} + +pub const fn id_for(channel: Channel) -> &'static str { + match channel { + Channel::Stable => APP_ID, + Channel::NightlyV1 => NIGHTLY_APP_ID, + } +} + +pub fn app_id() -> &'static str { + id_for(current()) +} + +pub const fn name_for(channel: Channel) -> &'static str { + match channel { + Channel::Stable => "GridCraft", + Channel::NightlyV1 => "GridCraft Nightly", + } +} + +pub fn name() -> &'static str { + name_for(current()) +} + +/// The title of a window that shows no document yet: the channel's own name. +pub fn default_title() -> &'static str { + name() +} + +/// Only a stable build runs the stable-only services (the updater, the shared suite state). +pub const fn stable_services_for(channel: Channel) -> bool { + matches!(channel, Channel::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(current()) +} + +/// The version to show: the selected build's own identity, else the crate version (a web build, +/// or a shell that never selected a channel). +pub fn version_for(channel: Channel, configured: Option<&'static str>) -> &'static str { + match (channel, configured) { + (Channel::NightlyV1, Some(version)) => version, + _ => env!("CARGO_PKG_VERSION"), + } +} + +pub fn version() -> &'static str { + version_for(current(), VERSION.get().copied()) +} + +/// The commit a nightly was built from, read back from its version (`…g`), if any. +/// +/// The producer writes the sha in lower case (the version pattern every nightly job enforces), so an +/// upper-case one is a malformed version rather than a commit: nothing is read back for it. +pub fn commit_for(version: &str) -> Option<&str> { + let (_, suffix) = version.split_once("-nightly.")?; + let (_, sha) = suffix.rsplit_once(".g")?; + (sha.len() == 12 && sha.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))).then_some(sha) +} + +pub fn commit() -> Option<&'static str> { + (current() == Channel::NightlyV1).then_some(version()).and_then(commit_for) +} + +/// A window title that names the channel whenever a document is shown in it. A stable window keeps +/// exactly the title it always had; a nightly one appends its channel, so two windows on the same +/// workbook are never mistaken for each other in the taskbar or the window menu. +pub fn window_title_for(channel: Channel, base: &str) -> String { + match channel { + Channel::Stable => base.to_string(), + Channel::NightlyV1 => format!("{base} \u{2014} {}", name_for(channel)), + } +} + +pub fn window_title(base: &str) -> String { + window_title_for(current(), base) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_two_channels_have_distinct_ids_and_names() { + assert_eq!(id_for(Channel::Stable), "ai.storyteller.gridcraft"); + assert_eq!(id_for(Channel::NightlyV1), "ai.storyteller.gridcraft.nightly-v1"); + assert_ne!(id_for(Channel::Stable), id_for(Channel::NightlyV1)); + // Three strings, not two: the Flatpak package id is not the window id, and neither is stable's. + assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.gridcraft.nightly"); + assert_ne!(NIGHTLY_PACKAGE_ID, id_for(Channel::NightlyV1)); + assert_ne!(NIGHTLY_PACKAGE_ID, id_for(Channel::Stable)); + assert_eq!(name_for(Channel::Stable), "GridCraft"); + assert_eq!(name_for(Channel::NightlyV1), "GridCraft Nightly"); + assert!(stable_services_for(Channel::Stable)); + assert!(!stable_services_for(Channel::NightlyV1)); + } + + #[test] + fn stable_titles_and_version_are_unchanged() { + for base in ["Book1", "Book1 — Edited", "", "sales.xlsx"] { + assert_eq!(window_title_for(Channel::Stable, base), base); + } + assert_eq!(version_for(Channel::Stable, Some("0.19.1-nightly.20261124.7.1.gabcdef012345")), env!("CARGO_PKG_VERSION")); + assert_eq!(version_for(Channel::Stable, None), env!("CARGO_PKG_VERSION")); + } + + #[test] + fn nightly_titles_name_the_channel_and_keep_the_document() { + assert_eq!(window_title_for(Channel::NightlyV1, "Book1"), "Book1 \u{2014} GridCraft Nightly"); + assert_eq!(window_title_for(Channel::NightlyV1, ""), " \u{2014} GridCraft Nightly"); + let nightly = "0.19.1-nightly.20261124.7.1.gabcdef012345"; + assert_eq!(version_for(Channel::NightlyV1, Some(nightly)), nightly); + assert_eq!(version_for(Channel::NightlyV1, None), env!("CARGO_PKG_VERSION"), "a nightly build without its own version is not invented"); + } + + #[test] + fn the_commit_is_read_back_only_from_a_nightly_version() { + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gabcdef012345"), Some("abcdef012345")); + assert_eq!(commit_for("0.19.1"), None); + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1"), None); + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gABCDEF012345"), None, "versions are lower-case"); + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gabcdef01234"), None); + } +} diff --git a/crates/ui-egui/src/dialogs/about.rs b/crates/ui-egui/src/dialogs/about.rs index a95878e924..c48c624923 100644 --- a/crates/ui-egui/src/dialogs/about.rs +++ b/crates/ui-egui/src/dialogs/about.rs @@ -15,8 +15,11 @@ pub(super) fn about(ui: &mut egui::Ui, d: &mut Dialog) { "Contributors" => crate::credits::contributors_ui(ui), "Models" => crate::credits::models_ui(ui), _ => { - ui.heading("GridCraft"); - ui.label(format!("Version {}", env!("CARGO_PKG_VERSION"))); + ui.heading(crate::channel::name()); + ui.label(format!("Version {}", crate::channel::version())); + if let Some(commit) = crate::channel::commit() { + ui.label(egui::RichText::new(format!("Built from {commit}")).small()); + } ui.add_space(4.0); ui.label("A clean-room, open-source, Rust-native spreadsheet. Part of ArtCraft."); ui.hyperlink_to("getartcraft.com/apps/gridcraft", "https://getartcraft.com/apps/gridcraft"); diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 7bf3a799d9..909770e9d7 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -257,7 +257,9 @@ fn visible_windows(app: &SheetApp) -> Vec { fn window_title(app: &SheetApp, window: u64) -> String { let title = app.session.window_title(window).unwrap_or_default(); let dirty = app.session.window(window).and_then(|w| app.session.documents().iter().find(|d| d.uid == w.doc_uid)).is_some_and(|d| d.is_dirty()); - if dirty { format!("{title} — Edited") } else { title } + let title = if dirty { format!("{title} — Edited") } else { title }; + // Nightly says which channel the window belongs to; stable titles are unchanged. + crate::channel::window_title(&title) } /// Outer rectangles for `n` windows arranged within `bounds` as View › Arrange All's `arrange` diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 65cca4d58a..97aacb3eee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -18,6 +18,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { pub mod backstage; mod border_preview; mod cell_pictures; +pub mod channel; mod chartcache; pub mod chartview; pub mod code_editor; diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 0000000000..1517a514ff --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,139 @@ +# 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 +adapted from `storytold/photocraft#16594`. Once `nightly.yml` lands on `main`, populate +`producer_workflow_id` before promoting the policy to `release`, read with: + +```bash +gh api repos/storytold/gridcraft/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 when to dispatch matters: +- 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 populate `producer_workflow_id` and +any Sonar debt snapshot) before the policy is promoted to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1408285582` | `gh api repos/storytold/gridcraft --jq .id` | +| `producer_workflow_id` | `null` (pending `main` registration) | Read with `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id` after `nightly.yml` lands on `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 who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows | Suite stable identities (Windows Authenticode publisher subject, Linux OpenPGP release key fingerprint, macOS Apple Developer ID team `DJ6XS33FX8`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135773`), 1 job (`gate / gate (ubuntu-24.04)`) | Workflow list API and recent green main push run | +| `candidate_policy.sonar` | `storytold` / `storytold_gridcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits | +| Sonar `issue_types` / `debt` | `VULNERABILITY` / `[]` | Refresh from `api/issues/search` on main before promoting to `release` | + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `GridCraft 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 (`gridcraft-nightly-release`) is distinct + from stable, cancellation is off and `queue: max` must be hosted-qualified. 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. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the GridCraft nightly source contract: +- Both callers share one pinned 40-hex commit in `uses` and `tooling-revision`. +- No cache actions, cache setup options, `environment:`, or `secrets` appear in the callers. +- No nightly schedule is registered. +- Producer and signer keep their exact context guards (every `if:` form and continuation line is read). +- Manual actors are exactly the reviewed release managers in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty. +- Root serialization in `nightly-sign.yml` remains literal (`group: gridcraft-nightly-release`, `cancel-in-progress: false`); it carries no `queue:` key while actionlint 1.7.12 rejects that key, and the value is re-added when the hosted queue is qualified. +- Installed policy v3 fields, bounds, platforms, candidate workflows, and Sonar identity match `sonar-project.properties` and the callers. + +## GridCraft's nightly-v1 flavor (the same branch) + +On top of the callers above, this branch makes the app a real `nightly-v1` channel: a nightly build is a +separate identity with its own data root, and every format starts it through the flavor's launch +protocol. None of this changes stable's behavior or the callers' authority. + +**Identity and version line.** `build.rs` maps `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` to +`cfg(gridcraft_nightly_v1)` and refuses any other value; a nightly build requires the prepared +`GRIDCRAFT_VERSION` and answers `--version` with exactly `GridCraft (nightly-v1)` — plain, +and in the Launcher's `--launch-profile nightly-v1 --profile-root --version` form, before any +root validation, logging, window or token. `packaging/nightly-common.sh`, `macos/nightly-verify.sh` +and `windows/nightly.ps1` compare that exact line, so the packaged scripts and the binary cannot +disagree. Stable still prints its Cargo version. + +**Data root.** A nightly starts from `--launch-profile nightly-v1 --profile-root

-- files…` +(separate tokens, refused in any other form) and keeps settings, prefs, logs and the control token +inside that folder; `profile_root` refuses the stable rows in both directions, a relative or +traversing root, a root that resolves through a link into a fenced folder, an inherited +`FLATPAK_ID` other than `ai.storyteller.gridcraft.nightly`, and the running installation. Users get +`${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile`, a sibling of stable's +`/gridcraft`, never an ancestor. + +**Every Linux format ships a launcher, and each passes an already-supplied profile through.** + +| Format | Launcher | GUI | Data root | +|---|---|---|---| +| deb/rpm | `/usr/bin/gridcraft-nightly` | `/usr/lib/gridcraft-nightly/gridcraft` | `/gridcraft-nightly/profile` | +| AppImage | `AppRun` (a script) and `usr/bin/gridcraft-nightly` | `usr/bin/gridcraft` | same | +| flat nightly tar | `gridcraft` | `gridcraft-bin` | same | +| plain tree tarball | `bin/gridcraft-nightly` | `bin/gridcraft` | same | +| Arch handoff | `bin/gridcraft-nightly` | `.gridcraft-nightly/gridcraft` | same | +| Flatpak bundle | `/app/bin/gridcraft-nightly` | `/app/bin/gridcraft` | the sandbox's own `~/.local/share` | + +The flat nightly tar uses the kit's standard layout: `` is the launcher people run and +`-bin` is the GUI ELF it starts, so the shared Unix verifier can keep requiring `gridcraft` +as the entrypoint. No launcher falls back to a relative or world-writable path for the GUI, and a +candidate that is the launcher itself is never started. + +**macOS and Windows.** `GridCraft Nightly.app` (`CFBundleIdentifier +ai.storyteller.gridcraft.nightly`, associations removed) is built and verified unsigned on main and +signed/notarized in the release signer; Windows gets a GUI-only x86_64 `.unsigned.zip` with the AUMID +`ai.storyteller.gridcraft.nightly-v1`, no MSI, no CLI and no portable marker. Both refuse signing +material during compilation. + +**Local checks.** `python3 packaging/nightly-tests.py` runs every synthetic suite in one pass: the +flat-archive policy, the macOS plist and sign/verify suites, the Linux launch and staging suites and +`packaging/nightly-release-tests.py`. `python3 packaging/nightly-icons.py --check` proves the +committed nightly icons still match `assets/app-icon/nightly-provenance.json`. `packaging-lint.yml` +runs both in its `nightly-source-contract` job. None of these compile the app or touch a key. + +**Still unqualified.** No hosted producer or signer run, no native signing, no Flatpak build and no +Linux/macOS desktop QA beside a stable install have happened for this flavor; the Rust unit tests +have only been type-checked where no capacity was available. Treat the first supervised run as the +first real qualification. diff --git a/packaging/icons.sh b/packaging/icons.sh index c6f325e3dd..f2d61c3a65 100755 --- a/packaging/icons.sh +++ b/packaging/icons.sh @@ -58,4 +58,7 @@ if command -v iconutil >/dev/null; then else echo "warning: iconutil not found (macOS only); gridcraft.icns not regenerated" >&2 fi +# The nightly channel's set: same artwork, deeper field; every frame rendered at its own size. +python3 "$ROOT/packaging/nightly-icons.py" + echo "icons written to $DIR" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 5ee85b3c55..9d276e92d7 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -17,6 +17,12 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.gridcraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${GRIDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 @@ -52,29 +58,79 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/gridcraft" ]] || { echo "error: $TARBALL has no bin/gridcraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + # The sandbox's own Flatpak id names the window (main.rs) and its data folder is already private, + # but the GUI still needs its launch profile: this launcher passes it, and the desktop entry and + # the manifest's one command name the launcher instead of the binary. + cat >"$WORK/stage/bin/gridcraft-nightly" <<'LAUNCHER' +#!/bin/sh +# GridCraft Nightly inside its own Flatpak: the launch profile is this app's private data folder. +set -eu +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "gridcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +case "${1-}" in + --launch-profile | --profile-root) exec /app/bin/gridcraft "$@" ;; +esac +if [ "$#" -eq 1 ] && { [ "${1-}" = "--version" ] || [ "${1-}" = "-V" ]; }; then + exec /app/bin/gridcraft "$@" +fi +exec /app/bin/gridcraft --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile" -- "$@" +LAUNCHER + chmod 755 "$WORK/stage/bin/gridcraft-nightly" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=gridcraft-nightly\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=gridcraft-nightly|" \ + -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=GridCraft$|Name=GridCraft Nightly|" \ + -e "s|^StartupWMClass=.*|StartupWMClass=$FLATPAK_ID|" \ + -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|$APP_ID|$FLATPAK_ID|g" \ + -e "s|GridCraft|GridCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|gridcraft|gridcraft-nightly|g" \ + -e '//d' \ + "$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/gridcraft-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" + # The manifest installs and runs the launcher; `command:` is what `flatpak run` starts. + sed -e "s|ai\.storyteller\.gridcraft|$FLATPAK_ID|g" \ + -e "s|^command: gridcraft$|command: gridcraft-nightly|" \ + -e "s|^ - install -Dm755 bin/gridcraft-cli /app/bin/gridcraft-cli$|&\n - install -Dm755 bin/gridcraft-nightly /app/bin/gridcraft-nightly|" \ + "$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=gridcraft-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=gridcraft-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" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 5e8c3a11a7..feee02f4d8 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # exports VERSION and NFPM_ARCH. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: gridcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -55,11 +55,14 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/gridcraft - dst: /usr/bin/gridcraft + - src: ${STAGE}/usr/lib/gridcraft-nightly/gridcraft + dst: /usr/lib/gridcraft-nightly/gridcraft file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/gridcraft-cli - dst: /usr/bin/gridcraft-cli + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} + file_info: { mode: 0755 } + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } - src: ${STAGE}/usr/share/ dst: /usr/share/ diff --git a/packaging/linux/nightly-arch-launch.sh b/packaging/linux/nightly-arch-launch.sh new file mode 100755 index 0000000000..ef22eea051 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# GridCraft Nightly for the Arch handoff: the GUI lives in .gridcraft-nightly/ beside this +# launcher. The launch profile is the only data root a nightly build accepts, and it holds the +# settings, logs, the control token and the session record, so no XDG variable has to move. +set -eu + +real_bin="$(dirname "$0")/.gridcraft-nightly/gridcraft" +# The Launcher's protocol and a bare version query name their own root and never read the default +# one, so they are dispatched before the guard that a default-root launch needs. +case "${1-}" in + --launch-profile | --profile-root) exec "$real_bin" "$@" ;; +esac +if [ "$#" -eq 1 ] && { [ "${1-}" = "--version" ] || [ "${1-}" = "-V" ]; }; then + exec "$real_bin" "$@" +fi +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "gridcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +exec "$real_bin" --launch-profile nightly-v1 \ + --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 0000000000..ebc6f6d4ae --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening GridCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=gridcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/gridcraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$stage/bin/gridcraft" +cp "$stage/bin/gridcraft" "$stage/bin/gridcraft-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/gridcraft" "$bin/gridcraft-nightly" +mv "$bin/gridcraft-cli" "$bin/gridcraft-nightly-cli" + +test ! -e "$stage/bin/.gridcraft-nightly" +cmp "$stage/bin/gridcraft" "$bin/.gridcraft-nightly/gridcraft" +cmp "$stage/bin/gridcraft-cli" "$bin/gridcraft-nightly-cli" + +# The launcher starts the GUI through the flavor's launch profile, its only data root. +data="$work/data" +profile="$data/gridcraft-nightly/profile" +expect() { + expected="$1" + shift + actual=$(XDG_DATA_HOME="$data" PATH="$bin:$PATH" gridcraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +nightly_argv() { + printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- +} +expect "$(nightly_argv)" +expect "$(nightly_argv; printf '<%s>\n' 'workbook with spaces.xlsx' '--other-name.xlsx')" \ + 'workbook with spaces.xlsx' '--other-name.xlsx' +# A bare version query and the Launcher's own protocol pass straight through. +expect '<--version>' --version +expect '<-V>' -V +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'book.xlsx')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'book.xlsx' +# A profile needs a data folder: the launcher refuses instead of writing into /. +status=0 +env -u XDG_DATA_HOME -u HOME PATH="$bin:$PATH" gridcraft-nightly book.xlsx >/dev/null 2>&1 || status=$? +[[ "$status" -eq 2 ]] || { printf 'expected exit 2 without XDG_DATA_HOME/HOME, got %s\n' "$status" >&2; exit 1; } +test ! -e "$data/gridcraft-nightly" +test ! -e "$work/launcher" + +echo "PASS: Arch Nightly handoff preserves launcher layout, profile selection and arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 0000000000..cc5dfc4a9b --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Stage the GridCraft 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/.gridcraft-nightly" +mv "$stage/bin/gridcraft" "$stage/bin/.gridcraft-nightly/gridcraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/gridcraft" +chmod 755 "$stage/bin/gridcraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 0000000000..48e120705b --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# GridCraft Nightly launcher for a moved tree: an AppImage (AppRun and usr/bin), the plain nightly +# tar, or a distro tarball's usr/bin. The launch profile is the only data root a nightly build +# accepts, so this is what keeps a Nightly run out of the stable app's settings, prefs and logs. +set -eu +here="$(cd "$(dirname "$0")" && pwd)" +# Where each placement keeps the GUI it starts: the AppImage (and any installed tree) has it in +# usr/bin/gridcraft; the flat nightly tar names it gridcraft-bin beside this launcher; a plain +# tree tarball keeps it beside its bin/gridcraft-nightly. A candidate that is this same file is +# never started, so a launcher can not recurse into itself. +self="$here/$(basename "$0")" +real="" +for candidate in "$here/usr/bin/gridcraft" "$here/gridcraft-bin" "$here/gridcraft"; do + if [ -x "$candidate" ] && [ ! "$candidate" -ef "$self" ]; then + real="$candidate" + break + fi +done +if [ -z "$real" ]; then + echo "gridcraft-nightly: no GridCraft binary beside $0 (usr/bin/gridcraft, gridcraft-bin)" >&2 + exit 2 +fi +# A bare version query and the Launcher's own protocol pass straight through: neither needs a data +# folder of this script's own, so neither may be refused for a HOME it never reads. +case "${1-}" in + --launch-profile | --profile-root) exec "$real" "$@" ;; +esac +if [ "$#" -eq 1 ] && { [ "${1-}" = "--version" ] || [ "${1-}" = "-V" ]; }; then + exec "$real" "$@" +fi +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "gridcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +exec "$real" --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile" -- "$@" diff --git a/packaging/linux/nightly-linux-launch-tests.py b/packaging/linux/nightly-linux-launch-tests.py new file mode 100644 index 0000000000..dff5ad53f1 --- /dev/null +++ b/packaging/linux/nightly-linux-launch-tests.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""The Linux launch profile, staged the way each format ships it; no cargo build, no GUI, no network. + +What is checked, all synthetic: + * `nightly-launch.sh` (the AppImage and tar launcher) passes the flavor's own tokens and nothing else; + * `package.sh` stages the deb/rpm, AppImage and tar launchers and a nightly desktop entry, and + leaves a stable tree exactly as it was. `nfpm`, `appimagetool` and `strip` are stubs on PATH. +""" +import os +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +LAUNCHER = ROOT / "packaging/linux/nightly-launch.sh" +PACKAGE = ROOT / "packaging/linux/package.sh" +NIGHTLY_VERSION = "0.19.1-nightly.20261124.7.1.gabcdef012345" +PROFILE = "gridcraft-nightly/profile" + +RECORDER = """#!/bin/sh +printf '<%s>\\n' "$@" +""" + + +def run(argv, cwd, env, check=True): + return subprocess.run(argv, cwd=cwd, env=env, check=check, capture_output=True, text=True) + + +class MovedTreeLauncher(unittest.TestCase): + """nightly-launch.sh as AppRun and as an unpacked tar's launcher.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.data = self.root / "data" + self.env = {"PATH": os.environ["PATH"], "XDG_DATA_HOME": str(self.data)} + + def install(self, layout): + """Each placement puts the GUI and this launcher where its format does. + + appdir: AppRun at the root, GUI in usr/bin (also usr/bin/gridcraft-nightly). + tar: the kit's flat tar, `gridcraft` launcher beside the `gridcraft-bin` GUI. + tree: a plain tree tarball, bin/gridcraft-nightly beside bin/gridcraft. + """ + tree = self.root / layout + binary, launcher_name = { + "appdir": (tree / "usr/bin/gridcraft", tree / "AppRun"), + "tar": (tree / "gridcraft-bin", tree / "gridcraft"), + "tree": (tree / "bin/gridcraft", tree / "bin/gridcraft-nightly"), + }[layout] + binary.parent.mkdir(parents=True) + binary.write_text(RECORDER) + binary.chmod(0o755) + shutil.copy2(LAUNCHER, launcher_name) + launcher_name.chmod(0o755) + return launcher_name + + def query(self, launcher, *args): + return run([str(launcher), *args], cwd=self.root, env=self.env) + + def tokens(self): + return ["<--launch-profile>", "", "<--profile-root>", f"<{self.data / PROFILE}>", "<-->"] + + def test_every_layout_starts_the_gui_through_the_launch_profile(self): + for layout in ("appdir", "tar", "tree"): + with self.subTest(layout=layout): + launcher = self.install(layout) + self.assertEqual(self.query(launcher).stdout.splitlines(), self.tokens()) + self.assertEqual( + self.query(launcher, "workbook with spaces.xlsx", "--other-name.xlsx").stdout.splitlines(), + self.tokens() + ["", "<--other-name.xlsx>"], + ) + + def test_a_bare_version_query_and_the_launcher_protocol_pass_through(self): + launcher = self.install("appdir") + for args in (["--version"], ["-V"], ["--launch-profile", "nightly-v1", "--profile-root", "/launcher", "--", "book.xlsx"]): + with self.subTest(args=args): + self.assertEqual(self.query(launcher, *args).stdout.splitlines(), [f"<{arg}>" for arg in args]) + + def test_a_missing_data_folder_or_binary_refuses_before_running_anything(self): + launcher = self.install("appdir") + refused = run([str(launcher), "book.xlsx"], cwd=self.root, env={"PATH": os.environ["PATH"]}, check=False) + self.assertEqual(refused.returncode, 2) + self.assertIn("XDG_DATA_HOME and HOME are both unset", refused.stderr) + (self.root / "appdir/usr/bin/gridcraft").unlink() + missing = run([str(launcher)], cwd=self.root, env=self.env, check=False) + self.assertEqual(missing.returncode, 2) + self.assertIn("no GridCraft binary", missing.stderr) + self.assertFalse(self.data.exists(), "a refused launch creates no data folder") + + def test_a_flat_tar_launcher_never_starts_itself(self): + launcher = self.install("tar") + (self.root / "tar/gridcraft-bin").unlink() + refused = run([str(launcher)], cwd=self.root, env=self.env, check=False) + self.assertEqual(refused.returncode, 2) + self.assertIn("no GridCraft binary", refused.stderr) + + def test_the_launcher_is_portable_shell(self): + run(["sh", "-n", str(LAUNCHER)], cwd=self.root, env=self.env) + self.assertTrue(LAUNCHER.read_text().startswith("#!/bin/sh\n")) + + +class FlatNightlyTar(unittest.TestCase): + """nightly.sh needs a release build, so its staging and the archive policy are source-guarded.""" + + def test_the_flat_tar_stages_the_kit_layout(self): + source = (ROOT / "packaging/linux/nightly.sh").read_text() + self.assertIn('cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin"', source, "the GUI is -bin") + self.assertIn('"$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft"', source, "the launcher is ") + self.assertNotIn('"$STAGE/gridcraft-nightly"', source, "the flat tar's launcher is gridcraft") + policy = (ROOT / "packaging/nightly-archive.py").read_text() + self.assertIn('{"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"}', policy) + self.assertIn('required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"', policy) + launcher = LAUNCHER.read_text() + self.assertIn('"$here/gridcraft-bin"', launcher, "the launcher starts the GUI the tar ships") + + +class StagedFormats(unittest.TestCase): + """package.sh with stub binaries, a stub nfpm and a stub strip.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.target = self.root / "target" + self.dist = self.root / "dist" + self.stubs = self.root / "stubs" + for directory in (self.target / "release", self.dist, self.stubs): + directory.mkdir(parents=True, exist_ok=True) + for name in ("gridcraft", "gridcraft-cli"): + binary = self.target / "release" / name + binary.write_text(RECORDER) + binary.chmod(0o755) + # `strip` would refuse the recorder scripts; the real one is a no-op for a non-ELF file too. + (self.stubs / "strip").write_text("#!/bin/sh\nexit 0\n") + (self.stubs / "strip").chmod(0o755) + (self.stubs / "nfpm").write_text( + '#!/bin/sh\n' + 'while [ "$#" -gt 0 ]; do [ "$1" = "-f" ] && cp "$2" "$STUB_NFPM_DIR/rendered.yaml"; shift; done\n' + 'exit 0\n' + ) + (self.stubs / "nfpm").chmod(0o755) + self.env = { + "PATH": f"{self.stubs}:{os.environ['PATH']}", + "HOME": os.environ.get("HOME", str(self.root)), + "CARGO_TARGET_DIR": str(self.target), + "DIST": str(self.dist), + "STUB_NFPM_DIR": str(self.root), + "GRIDCRAFT_BUILD_DATE": "2026-11-24", + "GRIDCRAFT_BUILD_SHA": "a" * 40, + } + + def stage(self, formats="deb tar", **extra): + env = dict(self.env, **extra) + run(["bash", str(PACKAGE), "--skip-build", "--formats", formats], cwd=ROOT, env=env) + return self.target / "linux-package" + + def nightly(self): + return self.stage(GRIDCRAFT_BUILD_CHANNEL="nightly-v1", GRIDCRAFT_VERSION=NIGHTLY_VERSION) + + def test_nightly_deb_installs_a_launcher_and_the_gui_beside_it(self): + work = self.nightly() + stage = work / "nfpm-root" + launcher = stage / "usr/bin/gridcraft-nightly" + gui = stage / "usr/lib/gridcraft-nightly/gridcraft" + self.assertTrue(self.executable(launcher)) + self.assertTrue(self.executable(gui)) + self.assertFalse((stage / "usr/bin/gridcraft").exists(), "the GUI moved out of usr/bin") + self.assertTrue(self.executable(stage / "usr/bin/gridcraft-nightly-cli")) + text = launcher.read_text() + self.assertIn('exec "/usr/lib/gridcraft-nightly/gridcraft" --launch-profile nightly-v1', text) + self.assertIn(f"/{PROFILE}", text) + self.assertEqual(gui.read_text(), RECORDER, "the packaged GUI is the built binary, unchanged") + rendered = (self.root / "rendered.yaml").read_text() + self.assertIn(f"src: {stage}/usr/lib/gridcraft-nightly/gridcraft", rendered) + self.assertIn("dst: /usr/lib/gridcraft-nightly/gridcraft", rendered) + self.assertIn("file_info: { mode: 0755 }", rendered) + + def test_nightly_desktop_and_metainfo_are_the_nightly_identity(self): + work = self.nightly() + applications = work / "nfpm-root/usr/share/applications" + desktop = applications / "ai.storyteller.gridcraft.nightly-v1.desktop" + self.assertEqual(sorted(p.name for p in applications.iterdir()), [desktop.name]) + text = desktop.read_text() + self.assertIn("Exec=gridcraft-nightly %F\n", text) + self.assertIn("TryExec=gridcraft-nightly\n", text) + self.assertIn("StartupWMClass=ai.storyteller.gridcraft.nightly-v1\n", text) + self.assertIn("Name=GridCraft Nightly\n", text) + self.assertNotIn("MimeType=", text) + metainfo = (work / "nfpm-root/usr/share/metainfo/ai.storyteller.gridcraft.nightly-v1.metainfo.xml").read_text() + self.assertNotIn("", metainfo) + self.assertIn("gridcraft-nightly", metainfo) + + def test_nightly_tar_ships_the_launcher_beside_the_binary(self): + self.nightly() + archive = self.dist / f"gridcraft-{NIGHTLY_VERSION}-linux-x86_64.tar.gz" + with tarfile.open(archive) as tar: + names = {member.name.split("/", 1)[-1] for member in tar.getmembers()} + launcher = tar.extractfile("gridcraft-%s-linux-x86_64/bin/gridcraft-nightly" % NIGHTLY_VERSION).read().decode() + binary = tar.extractfile("gridcraft-%s-linux-x86_64/bin/gridcraft" % NIGHTLY_VERSION).read().decode() + desktop = tar.extractfile("gridcraft-%s-linux-x86_64/share/applications/ai.storyteller.gridcraft.desktop" % NIGHTLY_VERSION).read().decode() + self.assertIn("bin/gridcraft", names) + self.assertEqual(binary, RECORDER) + self.assertEqual(launcher, LAUNCHER.read_text()) + self.assertIn("Exec=gridcraft-nightly %F\n", desktop) + self.assertIn("Name=GridCraft Nightly\n", desktop) + self.assertNotIn("MimeType=", desktop) + + def test_a_stable_tree_is_unchanged(self): + work = self.stage() + stage = work / "root" + self.assertEqual(stage, work / "root", "a stable build packages its one stage") + self.assertTrue(self.executable(stage / "usr/bin/gridcraft")) + self.assertTrue(self.executable(stage / "usr/bin/gridcraft-cli")) + self.assertFalse((stage / "usr/bin/gridcraft-nightly").exists()) + self.assertFalse((stage / "usr/lib").exists()) + rendered = (self.root / "rendered.yaml").read_text() + self.assertNotIn("gridcraft-nightly", rendered) + self.assertIn(f"src: {stage}/usr/bin/gridcraft\n", rendered) + desktop = (stage / "usr/share/applications/ai.storyteller.gridcraft.desktop").read_text() + self.assertIn("Exec=gridcraft %F\n", desktop) + self.assertIn("MimeType=", desktop) + with tarfile.open(self.dist / "gridcraft-0.19.1-linux-x86_64.tar.gz") as tar: + names = {member.name.split("/", 1)[-1] for member in tar.getmembers()} + self.assertIn("bin/gridcraft", names) + self.assertNotIn("bin/gridcraft-nightly", names) + + def test_nightly_appimage_runs_its_launcher_as_apprun(self): + tool = self.stubs / "appimagetool" + tool.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" >\"$STUB_NFPM_DIR/appimagetool.argv\"\n") + tool.chmod(0o755) + (self.stubs / "runtime").write_text("runtime fixture") + work = self.stage( + "appimage", + GRIDCRAFT_BUILD_CHANNEL="nightly-v1", + GRIDCRAFT_VERSION=NIGHTLY_VERSION, + APPIMAGETOOL=str(tool), + APPIMAGE_RUNTIME=str(self.stubs / "runtime"), + ) + appdir = work / "GridCraft.AppDir" + self.assertTrue(self.executable(appdir / "AppRun")) + self.assertEqual((appdir / "AppRun").read_text(), LAUNCHER.read_text(), "AppRun is the launcher, not a symlink") + self.assertFalse((appdir / "AppRun").is_symlink()) + self.assertEqual((appdir / "usr/bin/gridcraft-nightly").read_text(), LAUNCHER.read_text()) + self.assertEqual((appdir / "usr/bin/gridcraft").read_text(), RECORDER, "the binary stays in usr/bin") + desktop = (appdir / "usr/share/applications/ai.storyteller.gridcraft.nightly-v1.desktop").read_text() + self.assertIn("Exec=gridcraft-nightly %F\n", desktop) + self.assertIn("TryExec=gridcraft-nightly\n", desktop) + self.assertIn("StartupWMClass=ai.storyteller.gridcraft.nightly-v1\n", desktop) + self.assertNotIn("MimeType=", desktop) + + def executable(self, path): + self.assertTrue(path.is_file(), f"{path} is not a file") + self.assertTrue(os.access(path, os.X_OK), f"{path} is not executable") + return True + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 0000000000..9839623801 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +# shellcheck source=../nightly-common.sh +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/gridcraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +# The kit's tar layout: `gridcraft` is the launcher people run and `gridcraft-bin` is the GUI it +# starts. An unpacked archive is isolated too, because the GUI refuses to start without a launch +# profile and the launcher is the only thing that supplies one. +cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin" +chmod 755 "$STAGE/gridcraft-bin" +cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft" +chmod 755 "$STAGE/gridcraft" +# The nightly channel's own icon (deeper field); the archive member name stays as the helper requires. +cp "$ROOT/assets/app-icon/gridcraft-nightly.png" "$STAGE/gridcraft-nightly.png" +nightly_copy_notices "$STAGE" +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 466610d5c9..58b9c5faa9 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -5,9 +5,14 @@ # $DIST/gridcraft--linux-.AppImage.zsync delta updates (needs zsyncmake) # $DIST/gridcraft--linux-.deb Debian, Ubuntu, Mint, Pop!_OS, ... # $DIST/gridcraft--linux-.rpm Fedora, openSUSE, RHEL, ... -# $DIST/gridcraft--linux-.tar.gz plain FHS-style tree (bin/, share/) +# $DIST/gridcraft--linux-.tar.gz plain tree (bin/, share/) # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# A nightly build (`GRIDCRAFT_BUILD_CHANNEL=nightly-v1`) starts through the flavor's launcher in +# every format: usr/bin/gridcraft-nightly (deb/rpm, beside the GUI in usr/lib), the AppImage's +# AppRun script, and bin/gridcraft-nightly in the plain tree tarball. A nightly build refuses to +# start without `--launch-profile nightly-v1 --profile-root `, so every format ships one. +# +# 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 and the AppImage # runtime for the AppImage (pinned downloads into $CARGO_TARGET_DIR, or APPIMAGETOOL and @@ -22,10 +27,16 @@ APP_ID=ai.storyteller.gridcraft 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,18p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -39,9 +50,20 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export GRIDCRAFT_MAINTAINER="${GRIDCRAFT_MAINTAINER:-GridCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${GRIDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export GRIDCRAFT_BUILD_CHANNEL=nightly-v1 + export GRIDCRAFT_OVERRIDE_VERSION="$VERSION" +fi BASENAME="gridcraft-$VERSION-linux-$ARCH" -echo "==> GridCraft $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 "==> GridCraft $VERSION for Linux $ARCH ($FORMATS, channel=${GRIDCRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then @@ -60,6 +82,11 @@ install -Dm755 "$BIN/gridcraft" "$STAGE/usr/bin/gridcraft" install -Dm755 "$BIN/gridcraft-cli" "$STAGE/usr/bin/gridcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/gridcraft" "$STAGE/usr/bin/gridcraft-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.gridcraft.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@/$GRIDCRAFT_BUILD_DATE/g" \ @@ -81,21 +108,124 @@ has() { case " $FORMATS " in *" $format "*) return 0 ;; *) return 1 ;; esac } +# The deb/rpm launcher: /usr/bin/gridcraft-nightly starts the GUI from /usr/lib with this channel's +# own launch profile. A nightly build refuses to start without one, and the profile is the only +# data root it accepts, so a distro package can never share the stable app's settings, prefs or logs. +nightly_launcher() { + local destination="$1" real_bin="$2" + cat >"$destination" <&2 + exit 2 +fi +case "\${1-}" in + --launch-profile | --profile-root) exec "$real_bin" "\$@" ;; +esac +if [ "\$#" -eq 1 ] && { [ "\${1-}" = "--version" ] || [ "\${1-}" = "-V" ]; }; then + exec "$real_bin" "\$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "\${XDG_DATA_HOME:-\$HOME/.local/share}/gridcraft-nightly/profile" -- "\$@" +LAUNCHER + chmod 755 "$destination" +} + # ---- .tar.gz ------------------------------------------------------------------------------------ if has tar; then mkdir -p "$WORK/tar" cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + if [[ "$IS_NIGHTLY" = 1 ]]; then + # An unpacked nightly tar is isolated too: bin/gridcraft stays the binary, and the launcher + # beside it is how it starts (the binary itself refuses to run without a launch profile). + install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/gridcraft-nightly" + TAR_DESK="$WORK/tar/$BASENAME/share/applications/$APP_ID.desktop" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=gridcraft-nightly\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=gridcraft-nightly|" \ + -e "s|^Name=GridCraft$|Name=GridCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$TAR_DESK" >"$TAR_DESK.tmp" + mv "$TAR_DESK.tmp" "$TAR_DESK" + fi tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" 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="gridcraft" + export NFPM_BIN="gridcraft" + export NFPM_CLI="gridcraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="gridcraft-nightly" + export NFPM_BIN="gridcraft-nightly" + export NFPM_CLI="gridcraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + # The GUI keeps its name under /usr/lib; /usr/bin/-nightly is its launcher (see + # nightly_launcher), so the desktop entry never starts a binary that refuses to run. + install -Dm755 "$NFPM_STAGE/usr/bin/gridcraft" "$NFPM_STAGE/usr/lib/gridcraft-nightly/gridcraft" + rm -f "$NFPM_STAGE/usr/bin/gridcraft" + nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN" /usr/lib/gridcraft-nightly/gridcraft + mv "$NFPM_STAGE/usr/bin/gridcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI" + mv "$NFPM_STAGE/usr/share/doc/gridcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=GridCraft$|Name=GridCraft 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|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|GridCraft|GridCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|gridcraft|$NFPM_BIN|g" \ + -e "s|gridcraft-cli|$NFPM_CLI|g" \ + -e '//d' \ + "$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" + # The nightly files are different files: validate those too, not only the stable ones above. + if command -v desktop-file-validate >/dev/null; then + desktop-file-validate "$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + fi + if command -v appstreamcli >/dev/null; then + appstreamcli validate --no-net --explain "$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + fi + rm -rf "$NFPM_STAGE/usr/share/mime" + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/gridcraft-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" + # A nightly package keeps its GUI under /usr/lib behind usr/bin/gridcraft-nightly (see + # nightly_launcher). A stable tree has no such file, so this three-line entry is dropped and the + # rendered file stays exactly what main renders. + DROP_LIB_ENTRY= + # shellcheck disable=SC2016 + [[ -e "$NFPM_STAGE/usr/lib/gridcraft-nightly/gridcraft" ]] || DROP_LIB_ENTRY='\|^ - src: \${STAGE}/usr/lib/gridcraft-nightly/gridcraft|,+2d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_ENTRY}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|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 +261,33 @@ if has appimage; then } APPDIR="$WORK/GridCraft.AppDir" cp -R "$STAGE" "$APPDIR" - ln -s usr/bin/gridcraft "$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 + # A script, not the stable symlink: AppRun starts the GUI through its launch profile, and the + # desktop entry names the same launcher for integrations that read it. + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun" + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/usr/bin/gridcraft-nightly" + APPIMAGE_ID="$APP_ID.nightly-v1" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=gridcraft-nightly\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=gridcraft-nightly|" \ + -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=GridCraft$|Name=GridCraft 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/gridcraft-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/gridcraft "$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" ]] && [[ -z "$APPIMAGETOOL_SHA256" ]]; then @@ -160,7 +313,11 @@ if has appimage; then fi # Absolute, because appimagetool runs in $DIST below (CARGO_TARGET_DIR, APPIMAGETOOL or # APPIMAGE_RUNTIME may be relative, e.g. target/agent-). - OUT="$(cd "$DIST" && pwd)/$BASENAME.AppImage" + APPIMAGE_BASENAME="$BASENAME" + if [[ "$IS_NIGHTLY" = 1 && "$VERSION" != *-nightly* ]]; then + APPIMAGE_BASENAME="gridcraft-$VERSION-nightly-linux-$ARCH" + fi + OUT="$(cd "$DIST" && pwd)/$APPIMAGE_BASENAME.AppImage" APPDIR="$(cd "$APPDIR" && pwd)" TOOL="$(cd "$(dirname "$TOOL")" && pwd)/$(basename "$TOOL")" RUNTIME="$(cd "$(dirname "$RUNTIME")" && pwd)/$(basename "$RUNTIME")" @@ -171,11 +328,20 @@ 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/gridcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|gridcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|gridcraft-*-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|gridcraft-*-nightly*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + fi # Extract-and-run: works without FUSE (containers, CI). The output embeds the 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") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100755 index 0000000000..7097426fe2 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,117 @@ +# shellcheck shell=bash +# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh). +# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output +# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS. + +MAC_NIGHTLY_APP='GridCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.gridcraft.nightly' +# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh). +MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID) + +mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +# The exact prepared version from the feed asset name, or failure. +mac_nightly_version_from_asset() { + local name="$1" version + [[ "$name" =~ ^gridcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# The keychain import-cert.sh reports: a regular file inside this run's private WORK. This app's +# import-cert.sh creates it in a fresh directory of its own, so the path is not predicted here. +mac_nightly_keychain_is_ours() { + local keychain="$1" work="$2" + [[ -n "$keychain" && "$keychain" == "$work"/* && -f "$keychain" && ! -L "$keychain" ]] +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly +# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file' +import stat, sys, zipfile +archive, app = sys.argv[1:] +with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + name = info.filename + parts = name.rstrip("/").split("/") + mode = info.external_attr >> 16 + if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app + or any(part in ("", ".", "..") for part in parts) + or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)): + sys.exit(f"refused entry: {name!r}") +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 GridCraft +# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special +# files, no document or URL types. +mac_nightly_check_bundle() { + local payload="$1" version="$2" app entries plist key value + app="$payload/$MAC_NIGHTLY_APP" + entries="$(ls -A "$payload")" + [[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP" + [[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files' + [[ "$(ls -A "$app/Contents/MacOS")" == GridCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the GridCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/GridCraft" && -x "$app/Contents/MacOS/GridCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/GridCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable GridCraftVersion; do + value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key" + case "$key" in + CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;; + CFBundleExecutable) [[ "$value" == GridCraft ]] ;; + GridCraftVersion) [[ "$value" == "$version" ]] ;; + esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity" + done + for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do + if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi + done +} + +# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68) +# though the ticket is there (verify.sh). +mac_nightly_validate_staple() { + local target="$1" attempt + for attempt in 1 2 3 4 5; do + xcrun stapler validate "$target" && return 0 + [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) + done + return 1 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100755 index 0000000000..6d252e744f --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route +# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps): +# +# nightly-sign.sh --arch aarch64 --input /abs/gridcraft--macos-aarch64-nightly.zip \ +# --output /abs//gridcraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +# This app's import-cert.sh creates its keychain inside a fresh directory of its own +# (`mktemp -d "$BASE/gridcraft-signing.XXXXXXXX"/gridcraft-signing.keychain-db`), so the name is +# read back from it instead of being predicted here; it must still live inside this run's WORK. +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/gridcraft-nightly-sign.XXXXXX")" +cleanup() { + if [[ -n "${KEYCHAIN:-}" && -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" +if [[ ! "$IDENTITY" =~ ^[0-9A-F]{40}$ ]] || ! mac_nightly_keychain_is_ours "$KEYCHAIN" "$WORK"; then + mac_nightly_die 'import-cert.sh did not import a signing identity into this run' +fi +mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \ + || mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID" +echo "==> GridCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY" + +# ---- the unsigned bundle --------------------------------------------------------------------------- +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +# ---- package.sh's signing and notarization, with a required Developer ID --------------------------- +sign() { + codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@" +} + +notarize() { + local file="$1" out id status + echo "==> notarizing $(basename "$file") (this can take a few minutes)" + out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true + echo "$out" + id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" + status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then + # Capped: the shared signer bounds a step's output at 256 KiB. + xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true + fi + echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 + exit 1 + fi +} + +# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the +# connection right after notarization (error 68), so retry the pair (package.sh). +staple() { + local file="$1" attempt + for attempt in 1 2 3 4 5; do + if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then + return + fi + if [[ "$attempt" = 5 ]]; then + echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2 + exit 1 + fi + echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2 + sleep $((attempt * 20)) + done +} + +# Inside-out: the executable, then the bundle (no --deep on the final signature). +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/GridCraft" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" +ditto -c -k --keepParent "$APP" "$WORK/notarize.zip" +notarize "$WORK/notarize.zip" +# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs. +staple "$APP" + +# ---- the final archive, checked as the Launcher unpacks it ----------------------------------------- +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip" +ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check" +mac_nightly_check_bundle "$WORK/check" "$VERSION" +CHECK="$WORK/check/$MAC_NIGHTLY_APP" +codesign --verify --strict --deep --verbose=2 "$CHECK" +mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \ + || mac_nightly_die 'the signed bundle is not the required Developer ID signature' +mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle' +# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh). +for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 +done +printf '%s\n' "$assessment" +mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' + +nightly_publish_archive "$WORK/final.zip" "$OUTPUT" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100755 index 0000000000..1e137b3a56 --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version. +# For a job without signing material (it refuses to run with any), after nightly-sign.sh: +# +# nightly-verify.sh --input /abs/gridcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/gridcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact GridCraftVersion, unpacked +# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else +# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as +# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature. +# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the +# Launcher's form `--launch-profile nightly-v1 --profile-root --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `GridCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/gridcraft-nightly-verify.XXXXXX")" +trap 'rm -rf -- "$WORK"' EXIT +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +if [[ "$EXPECT" == signed ]]; then + codesign --verify --strict --deep --verbose=2 "$APP" + mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \ + || mac_nightly_die 'the bundle is not the required Developer ID signature' + mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle' + for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 + done + printf '%s\n' "$assessment" + mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' +fi + +# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say). +query() { + local out + out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \ + /usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/GridCraft" "$@" 2>"$WORK/stderr")" \ + || mac_nightly_die "the version query ($*) failed or did not finish within 15 s" + [[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")" + [[ "$out" == "GridCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not GridCraft $VERSION (nightly-v1)" +} +mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile" +query --version +query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version +echo "==> verified ($EXPECT): GridCraft $VERSION (nightly-v1), plain and in the Launcher's profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 0000000000..aa1f60fce5 --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/gridcraft--macos-aarch64-nightly.zip GridCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): GRIDCRAFT_BUILD_CHANNEL=nightly-v1, GRIDCRAFT_VERSION, +# GRIDCRAFT_BUILD_SHA, GRIDCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional. +# +# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI, +# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query +# runs on the signed bundle (nightly-verify.sh). +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; } +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +. "$HERE/../nightly-common.sh" +. "$HERE/nightly-lib.sh" +nightly_refuse_signing_env +nightly_init macos "$ARCH" aarch64-apple-darwin +# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh). +export MACOSX_DEPLOYMENT_TARGET=11.0 +OUTPUT="$DIST/gridcraft-$VERSION-macos-aarch64-nightly.zip" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_compile_gui + +APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/GridCraft" +chmod 755 "$APP/Contents/MacOS/GridCraft" +cp "$ROOT/assets/app-icon/gridcraft-nightly.icns" "$APP/Contents/Resources/gridcraft-nightly.icns" +nightly_copy_notices "$APP/Contents/Resources" +# The private mktemp cwd is the helper authority root: stage the template inside it. +cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" +(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ + --output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$GRIDCRAFT_BUILD_SHA") +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION" + +# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them. +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip" +nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100755 index 0000000000..e926399f0b --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.gridcraft.nightly" +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="GridCraft Nightly", + CFBundleName="GridCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="GridCraft", + CFBundleIconFile="gridcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + GridCraftVersion=version, + GridCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100755 index 0000000000..469e715b44 --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.gridcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "GridCraft") + self.assertEqual(rendered["GridCraftVersion"], VERSION) + self.assertEqual(rendered["GridCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["GridCraftVersion"], VERSION) + self.assertEqual(result["GridCraftBuildCommit"], COMMIT) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_template_alias_or_nonfile_refuses_before_output(self): + alias = self.root / "template-alias" + alias.symlink_to(self.template) + for template in (alias, self.root, self.root / "missing-template"): + with self.subTest(template=template), self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self): + sentinel = b"generated replacement artifact" + for disposition in ("owned", "missing", "replacement"): + with self.subTest(disposition=disposition): + if self.output.exists(): + self.output.unlink() + + def fail_sync(_descriptor): + # macOS/Linux allow unlink of an open file: exercise the real + # cleanup ownership check, not a mocked inode comparison. + if disposition != "owned": + self.output.unlink() + if disposition == "replacement": + self.output.write_bytes(sentinel) + raise OSError("generated fsync failure") + + with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + if disposition == "replacement": + self.assertEqual(self.output.read_bytes(), sentinel) + else: + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self): + sentinel = b"generated owned sentinel, not an existing app or user file" + self.output.write_bytes(sentinel) + with self.assertRaises(FileExistsError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(self.output.read_bytes(), sentinel) + self.output.unlink() + external = self.root / "sentinel" + external.write_bytes(sentinel) + self.output.symlink_to(external) + with self.assertRaisesRegex(ValueError, "symlinks or aliases"): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(external.read_bytes(), sentinel) + self.assertTrue(self.output.is_symlink()) + + + def test_template_outside_build_root_refuses_before_output(self): + with tempfile.TemporaryDirectory() as external: + template = Path(external) / "Info.plist.in" + template.write_bytes(self.original) + with self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(template.read_bytes(), self.original) + + def test_output_outside_build_root_refuses_before_write(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse(output.exists()) + + def test_parent_traversal_refuses_even_to_an_owned_sibling(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_symlinked_output_parent_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_template_read_is_bounded_before_output(self): + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_nonprivate_build_root_refuses(self): + self.root.chmod(0o755) + try: + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + finally: + self.root.chmod(0o700) + + + def test_output_keeps_normal_new_file_permissions_inside_private_root(self): + previous = os.umask(0o022) + try: + reference = self.root / "reference" + reference.write_bytes(b"generated ordinary output") + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + finally: + os.umask(previous) + self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777) + + def test_open_parent_anchor_prevents_a_later_alias_redirect(self): + parent = self.root / "stage" + parent.mkdir() + retained = self.root / "retained-stage" + destination = parent / "Info.plist" + original = POLICY.OwnedBuildRoot._parent + with tempfile.TemporaryDirectory() as external: + def swap_after_parent_open(root, path): + descriptor, name = original(root, path) + if Path(path) == destination: + parent.rename(retained) + parent.symlink_to(external, target_is_directory=True) + return descriptor, name + with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open): + POLICY.write_plist(self.template, destination, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["GridCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100755 index 0000000000..0a4535206a --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated +fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil, +lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a +real signature, notarization or Mac run.""" +import base64 +import importlib.util +import json +import os +from pathlib import Path +import plistlib +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +import zipfile + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py") +PLIST = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PLIST) +COMMIT = "b" * 40 +VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12] +ASSET = f"gridcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "GridCraft Nightly.app" +TEAM = "ABCDE12345" +IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567" +SECRETS = { + "APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(), + "APPLE_CERTIFICATE_PASSWORD": "generated-fixture", + "KEYCHAIN_PASSWORD": "generated-fixture", + "APPLE_ID": "fixture@example.invalid", + "APPLE_PASSWORD": "generated-fixture", + "APPLE_TEAM_ID": TEAM, +} + +# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line. +SHIM = r""" +import json, os, plistlib, sys, zipfile +from pathlib import Path +name = Path(sys.argv[0]).name +args = sys.argv[1:] +with open(os.environ["SHIM_LOG"], "a") as log: + log.write(json.dumps([name] + args) + "\n") +team = os.environ.get("SHIM_TEAM", "") +if name == "uname": + print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin")) +elif name == "lipo": + print("arm64") +elif name == "ditto": + paths = [a for a in args if not a.startswith("-")] + src, dst = paths + if "-x" in args: + with zipfile.ZipFile(src) as z: + for info in z.infolist(): + target = Path(dst) / info.filename + if info.is_dir(): + target.mkdir(parents=True, exist_ok=True) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(z.read(info)) + mode = (info.external_attr >> 16) & 0o777 + if mode: + target.chmod(mode) + else: + root = Path(src) + with zipfile.ZipFile(dst, "x") as z: + for path in sorted([root] + list(root.rglob("*"))): + arc = (Path(root.name) / path.relative_to(root)).as_posix() + if path.is_dir(): + z.writestr(zipfile.ZipInfo(arc + "/"), b"") + else: + info = zipfile.ZipInfo(arc) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, path.read_bytes()) +elif name == "plutil": + if args[0] == "-lint": + sys.exit(0) + key, fmt, source = args[1], args[2], args[-1] + data = sys.stdin.read() if source == "-" else Path(source).read_bytes() + value = json.loads(data) if source == "-" else plistlib.loads(data) + if key not in value: + sys.exit(1) + print(value[key] if fmt == "raw" else "") +elif name == "security": + verb = args[0] + if verb == "create-keychain": + Path(args[-1]).write_bytes(b"keychain") + elif verb == "find-identity": + print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team)) + print(" 1 valid identities found") + elif verb == "delete-keychain": + Path(args[-1]).unlink() +elif name == "codesign": + target = Path(args[-1]) + if "--sign" in args and target.suffix == ".app": + (target / "Contents/_CodeSignature").mkdir(exist_ok=True) + (target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed") + if "-d" in args: + sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.gridcraft.nightly\n" + "CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n" + "Authority=Developer ID Application: Generated Fixture (%s)\n" + "Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team)) +elif name == "xcrun": + if args[:2] == ["notarytool", "submit"]: + print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")})) + elif args[:2] == ["stapler", "staple"]: + (Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket") + elif args[:2] == ["stapler", "validate"]: + sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1) +elif name == "spctl": + sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1]) +elif name == "cargo": + sys.exit(1) +# sleep: the retry waits pass at once. +""" + +TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep") + + +class Fixture: + def __init__(self, test): + self.directory = tempfile.TemporaryDirectory() + test.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + self.bin = self.root / "bin" + self.bin.mkdir() + shim = self.bin / "shim.py" + shim.write_text(SHIM) + for tool in TOOLS: + path = self.bin / tool + path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n") + path.chmod(0o755) + self.log = self.root / "tools.log" + self.ran = self.root / "payload-ran" + self.temp = self.root / "runner-temp" + self.temp.mkdir() + self.dist = self.root / "unsigned" + self.dist.mkdir() + self.signed = self.root / "signed" + self.signed.mkdir() + self.input = self.dist / ASSET + self.output = self.signed / ASSET + # Every script runs from a directory with modules a Python helper must not import (-I). + self.cwd = self.root / "cwd" + self.cwd.mkdir() + self.hijacked = self.root / "hijacked" + for module in ("shutil", "zipfile", "stat"): + (self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n") + + def add_entry(self, info, data=b""): + """Append one raw entry to the input archive.""" + with zipfile.ZipFile(self.input, "a") as z: + z.writestr(info, data) + + def bundle(self, version=VERSION, extra=None, gui=None): + """The archive nightly.sh makes: the real template through the real plist helper.""" + stage = self.root / "stage" + shutil.rmtree(stage, ignore_errors=True) + app = stage / APP + (app / "Contents/MacOS").mkdir(parents=True) + (app / "Contents/Resources").mkdir() + exe = app / "Contents/MacOS/GridCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'GridCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/gridcraft-nightly.icns").write_bytes(b"generated icon") + rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT) + (app / "Contents/Info.plist").write_bytes(rendered) + for relative, data in (extra or {}).items(): + (app / relative).write_bytes(data) + (app / relative).chmod(0o755) + if self.input.exists(): + self.input.unlink() + with zipfile.ZipFile(self.input, "x") as z: + for path in sorted([app] + list(app.rglob("*"))): + arc = (Path(APP) / path.relative_to(app)).as_posix() + info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else "")) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, b"" if path.is_dir() else path.read_bytes()) + return self.input + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log), + "SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS} + env.update(changes) + return {key: value for key, value in env.items() if value is not None} + + def run(self, script, *args, **env): + if self.log.exists(): + self.log.unlink() + return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + + def sign(self, **env): + return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env) + + def calls(self): + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text().splitlines()] + + +def lib(function, *args): + """Run one nightly-lib.sh function; returns (exit status, stdout).""" + script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"' + result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + return result.returncode, result.stdout.strip() + + +DETAILS = (f"Identifier=ai.storyteller.gridcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n" + f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n" + f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n") + + +class Checks(unittest.TestCase): + def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self): + self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION)) + for name in (f"gridcraft-0.23.1-macos-aarch64.zip", f"gridcraft-{VERSION}-macos-universal-nightly.zip", + f"gridcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET): + with self.subTest(name=name): + self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0) + + def test_signature_needs_every_part_of_the_developer_id_signature(self): + self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0) + for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"), + DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"), + "Identifier=gridcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.gridcraft.nightly", "ai.storyteller.gridcraft"), + DETAILS.replace("ai.storyteller.gridcraft.nightly", "aiXstorytellerXgridcraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_signing_keychain_must_be_a_regular_file_inside_the_run(self): + # This app's import-cert.sh makes its own directory for the keychain, so the night's + # script accepts any path inside WORK - and nothing outside it, and no link. + with tempfile.TemporaryDirectory() as work: + work = Path(work).resolve() + nested = work / "gridcraft-signing.fixture" + nested.mkdir() + keychain = nested / "gridcraft-signing.keychain-db" + keychain.write_bytes(b"generated fixture") + self.assertEqual(lib("mac_nightly_keychain_is_ours", keychain, work)[0], 0) + outside = Path(tempfile.mkdtemp()) / "gridcraft-signing.keychain-db" + self.addCleanup(shutil.rmtree, outside.parent) + outside.write_bytes(b"generated fixture") + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", outside, work)[0], 0, "another directory's keychain") + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", work / "missing.keychain-db", work)[0], 0) + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", "", work)[0], 0) + link = work / "linked.keychain-db" + link.symlink_to(keychain) + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", link, work)[0], 0, "a link is not the keychain it points at") + + def test_the_imported_identity_must_be_a_developer_id_of_the_team(self): + line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"' + self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0) + + +class Sign(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + self.f.bundle() + self.unsigned = self.f.input.read_bytes() + + def assert_refused_untouched(self, result, signed=False): + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.output.exists()) + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + names = [call[0] for call in self.f.calls()] + self.assertNotIn("cargo", names) + if not signed: + self.assertNotIn("codesign", names) + self.assertNotIn("xcrun", names) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + + def test_signs_notarizes_and_staples_without_running_the_payload(self): + result = self.f.sign() + self.assertEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets") + calls = self.f.calls() + names = [call[0] for call in calls] + self.assertNotIn("cargo", names) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + signs = [call for call in calls if call[0] == "codesign" and "--sign" in call] + self.assertEqual([Path(call[-1]).name for call in signs], ["GridCraft", APP], "inside-out: executable, then bundle") + for call in signs: + for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY): + self.assertIn(flag, call) + order = [" ".join(call[:3]) for call in calls] + submit = order.index("xcrun notarytool submit") + staple = order.index("xcrun stapler staple") + self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit) + self.assertLess(submit, staple) + final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1] + self.assertLess(staple, final, "the final archive carries the stapled ticket") + self.assertIn("--noextattr", calls[final]) + self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls]) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + with zipfile.ZipFile(self.f.output) as z: + names = set(z.namelist()) + self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle") + self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names) + self.assertTrue(all(name.startswith(APP) for name in names)) + mode = z.getinfo(f"{APP}/Contents/MacOS/GridCraft").external_attr >> 16 + self.assertTrue(mode & stat.S_IXUSR) + + def test_every_signing_and_notarization_secret_is_required(self): + for name in SECRETS: + with self.subTest(missing=name): + self.assert_refused_untouched(self.f.sign(**{name: None})) + self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete") + self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999")) + self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team")) + + def test_refuses_another_team_s_identity(self): + self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999")) + + def test_never_replaces_an_output_or_renames_the_asset(self): + self.f.output.write_bytes(b"generated existing artifact") + result = self.f.sign() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact") + self.f.output.unlink() + renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip") + self.assertNotEqual(renamed.returncode, 0) + relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output) + self.assertNotEqual(relative.returncode, 0) + self.assertEqual(list(self.f.signed.iterdir()), []) + + def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self): + cases = { + "cli": dict(extra={"Contents/MacOS/gridcraft-cli": b"generated cli"}), + "version": dict(version=VERSION.replace("4567", "4568")), + } + for label, change in cases.items(): + with self.subTest(label=label): + self.f.bundle(**change) + self.unsigned = self.f.input.read_bytes() + self.assert_refused_untouched(self.f.sign()) + + def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self): + link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link") + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo") + fifo.external_attr = (stat.S_IFIFO | 0o644) << 16 + for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")), + ("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))): + with self.subTest(label=label): + self.f.bundle() + self.f.add_entry(info, b"/etc/passwd") + self.unsigned = self.f.input.read_bytes() + result = self.f.sign() + self.assert_refused_untouched(result) + self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking") + + def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self): + result = self.f.sign(SHIM_NOTARY="Invalid") + self.assert_refused_untouched(result, signed=True) + self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()]) + self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()]) + + +class Verify(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + + def verify(self, *args, **env): + return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env) + + def test_asks_the_gui_its_version_with_an_empty_environment(self): + self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'GridCraft {VERSION} (nightly-v1)'\n") + result = self.verify("--expect", "unsigned", INHERITED="generated") + self.assertEqual(result.returncode, 0, result.stdout) + self.f.bundle(gui="#!/bin/sh\necho 'GridCraft 0.23.1 (stable)'\n") + self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0) + + def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self): + answer = f"echo 'GridCraft {VERSION} (nightly-v1)'" + # The shared producer smoke's exact form, with a fresh profile directory. + exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n' + ' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n' + f'fi\n{answer}\n') + self.f.bundle(gui=exact) + result = self.verify("--expect", "unsigned") + self.assertEqual(result.returncode, 0, result.stdout) + hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n' + self.f.bundle(gui=hangs) + started = time.monotonic() + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("within 15 s", result.stdout) + self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for") + noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n' + self.f.bundle(gui=noisy) + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("standard error", result.stdout) + + def test_a_signed_check_needs_the_signature_ticket_and_team(self): + self.f.bundle() + self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against") + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket") + self.f.bundle(extra={"Contents/CodeResources": b"ticket"}) + self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0) + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0) + + def test_refuses_to_run_the_payload_beside_signing_material(self): + self.f.bundle() + for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"): + with self.subTest(name=name): + result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned", + **{**{key: None for key in SECRETS}, name: "generated"}) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.f.ran.exists()) + self.assertEqual(self.f.calls(), []) + + +class Build(unittest.TestCase): + def test_compilation_refuses_signing_material_before_building(self): + f = Fixture(self) + for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"): + with self.subTest(name=name): + result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"}, + GRIDCRAFT_BUILD_CHANNEL="nightly-v1", GRIDCRAFT_VERSION=VERSION) + self.assertNotEqual(result.returncode, 0) + self.assertIn(name, result.stdout) + self.assertNotIn("cargo", [call[0] for call in f.calls()]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100755 index 0000000000..9487b31904 --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + # The kit's tar layout: `gridcraft` runs, `gridcraft-bin` is the GUI it starts. + self.required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "gridcraft").chmod(0o755) + (self.stage / "gridcraft-bin").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("gridcraft").read(), (self.stage / "gridcraft").read_bytes()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["gridcraft-cli", "portable.txt", "gridcraft.desktop", "gridcraft-nightly"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "gridcraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "gridcraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 0000000000..490bf19336 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + # `gridcraft` is the launcher and `gridcraft-bin` the GUI it starts (nightly.sh); the icon + # and the notices are the rest of the flat archive. + if name not in {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + with root.reader(entry, MAX_MEMBER_BYTES) as stream: + total += os.fstat(stream.fileno()).st_size + if total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage exceeds its read bound") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + info = tarfile.TarInfo(os.path.basename(destination)) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 0000000000..69460ad2b5 --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,97 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${GRIDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'GRIDCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${GRIDCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${GRIDCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${GRIDCRAFT_VERSION##*.g}" == "${GRIDCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${GRIDCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${GRIDCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${GRIDCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$GRIDCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + # shellcheck source=env.sh + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: macOS runs the version query after signing (packaging/macos/nightly-verify.sh). +nightly_compile_gui() { + # `build.rs` reads GRIDCRAFT_VERSION (it bakes it as GRIDCRAFT_BUILT_VERSION, the value the + # binary answers `--version` with), so the prepared identity is passed explicitly here as well as + # through the inherited environment; VERSION is that same value (see env.sh). + nightly_refuse_signing_env + (cd "$ROOT" && GRIDCRAFT_VERSION="$VERSION" GRIDCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p gridcraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/gridcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$GRIDCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + # Exactly what the flavor prints (`build_flavor::version` in apps/gridcraft): the prepared + # version followed by the build channel. A stable build prints the Cargo version instead. + [[ "$actual" == "GridCraft $VERSION (nightly-v1)" ]] \ + || nightly_die "the built identity is '$actual', not 'GridCraft $VERSION (nightly-v1)'" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$GRIDCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 -I - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-icons.py b/packaging/nightly-icons.py new file mode 100755 index 0000000000..c0a67608a1 --- /dev/null +++ b/packaging/nightly-icons.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Render the GridCraft Nightly icon set from assets/app-icon/gridcraft-nightly.svg. + +The stable set is made by packaging/icons.sh (resvg + `cargo xtask ico` + iconutil). This does the +same for the Nightly channel, with the same geometry: Windows and Linux use the full-bleed tile, +macOS uses the 824/1024 padded tile. Every frame is rendered at its own size; nothing is upscaled. + +Needs one vector renderer: `resvg` (what icons.sh uses), else a headless Chrome +(`chrome-headless-shell` or `chromium`/`google-chrome`) drawing the SVG on a transparent page at +device scale 1. The `.ico` and `.icns` containers are written here so the set needs no macOS. + +Usage: packaging/nightly-icons.py [--renderer auto|resvg|chrome] [--check] + +--check verifies the committed files still match assets/app-icon/nightly-provenance.json and that +each PNG/ICO/ICNS member has the size its slot says, without rendering anything. +""" +import argparse +import hashlib +import html +import json +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile +import zlib + +ROOT = Path(__file__).resolve().parents[1] +ICONS = ROOT / "assets" / "app-icon" +SVG = ICONS / "gridcraft-nightly.svg" +# The macOS tile is the full-bleed 512-square viewBox widened so the body fills 824 of 1024 px. +MAC_VIEWBOX = 'viewBox="-62.136 -62.136 636.272 636.272"' +ICO_SIZES = (16, 20, 24, 32, 40, 48, 64, 128, 256) +# The ICNS slots iconutil writes, and macOS still reads. +ICNS_SLOTS = ( + ("icp4", 16), ("icp5", 32), ("ic11", 32), ("icp6", 64), ("ic12", 64), ("ic07", 128), + ("ic08", 256), ("ic13", 256), ("ic09", 512), ("ic14", 512), ("ic10", 1024), +) +MAC_PNG_SIZES = (16, 32, 64, 128, 256, 512, 1024) +CHROME_NAMES = ("chrome-headless-shell", "chromium", "chromium-browser", "google-chrome", "google-chrome-stable") + + +def die(message): + raise SystemExit(f"nightly-icons: {message}") + + +def renderer_argv(kind): + if kind in ("auto", "resvg"): + found = shutil.which("resvg") + if found: + return ("resvg", found) + if kind == "resvg": + die("resvg not found (brew install resvg / cargo install resvg)") + for name in CHROME_NAMES: + found = shutil.which(name) + if found: + return ("chrome", found) + die("no vector renderer found: install resvg, or a headless Chrome") + + +def render_resvg(resvg, svg_text, size, out): + with tempfile.TemporaryDirectory() as work: + source = Path(work) / "icon.svg" + source.write_text(svg_text) + subprocess.run([resvg, "-w", str(size), "-h", str(size), str(source), str(out)], check=True, stdin=subprocess.DEVNULL) + + +def render_chrome(chrome, svg_text, size, out): + # The SVG's width/height attributes fix the document size; the page is exactly that. + start = svg_text.index("", start) + tag = svg_text[start:end] + for attribute in (' width="512"', ' height="512"'): + tag = tag.replace(attribute, "") + tag = f'{tag} width="{size}" height="{size}"' + page = ( + "" + + svg_text[:start] + tag + svg_text[end:] + + "" + ) + with tempfile.TemporaryDirectory() as work: + document = Path(work) / "icon.html" + document.write_text(page) + subprocess.run( + [chrome, "--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", + "--default-background-color=00000000", "--force-device-scale-factor=1", + f"--window-size={size},{size}", f"--screenshot={out}", document.as_uri()], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + +def png_size(data): + if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR": + die("renderer wrote something that is not a PNG") + return struct.unpack(">II", data[16:24]) + + +def has_alpha(data): + # IHDR colour type 6 is RGBA; a renderer that dropped alpha would flatten the padding. + return data[25] == 6 + + +def pack_ico(pngs): + body = bytearray(struct.pack(" 256: + die(f"ico frames must be square and at most 256 px, got {width}x{height}") + body += struct.pack("I", len(data) + 8) + data + return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body) + + +def mac_svg(svg_text): + if 'viewBox="0 0 512 512"' not in svg_text: + die("gridcraft-nightly.svg must keep the full-bleed 0 0 512 512 viewBox") + return svg_text.replace('viewBox="0 0 512 512"', MAC_VIEWBOX) + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def render_all(kind): + renderer, program = renderer_argv(kind) + svg_text = SVG.read_text() + padded = mac_svg(svg_text) + with tempfile.TemporaryDirectory() as work: + work = Path(work) + + def draw(source, size, name): + if not source.strip(): + die(f"empty SVG for {name}") + out = work / "tile.svg" + out.write_text(source) + (render_resvg if renderer == "resvg" else render_chrome)(program, source, size, work / name) + data = (work / name).read_bytes() + if png_size(data) != (size, size): + die(f"{name}: expected {size}x{size}, got {png_size(data)}") + if not has_alpha(data): + die(f"{name}: the render has no alpha channel") + return data + + # Full-bleed tile: the Linux tar icon (256) and the Windows ICO frames. + tile = {size: draw(svg_text, size, f"tile-{size}.png") for size in sorted({256} | set(ICO_SIZES))} + (ICONS / "gridcraft-nightly.png").write_bytes(tile[256]) + (ICONS / "gridcraft-nightly.ico").write_bytes(pack_ico([tile[size] for size in ICO_SIZES])) + # Padded macOS tile: the 1024 master, the ICNS slots and the runtime Dock render. + mac = {size: draw(padded, size, f"mac-{size}.png") for size in MAC_PNG_SIZES} + (ICONS / "gridcraft-nightly-1024.png").write_bytes(mac[1024]) + (ICONS / "gridcraft-nightly.icns").write_bytes(pack_icns([(kind, mac[size]) for kind, size in ICNS_SLOTS])) + write_provenance(renderer) + + +def write_provenance(renderer): + outputs = ("gridcraft-nightly.png", "gridcraft-nightly-1024.png", "gridcraft-nightly.ico", "gridcraft-nightly.icns") + provenance = { + "title": "GridCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": [ + {"path": "assets/app-icon/gridcraft-nightly.svg", "sha256": digest(SVG), "purpose": "vector master for every frame"}, + {"path": "assets/app-icon/gridcraft.svg", "sha256": digest(ICONS / "gridcraft.svg"), "purpose": "stable artwork this is derived from"}, + ], + "method": { + "kind": "vector render of the project-owned artwork with only its field colour deepened", + "stable_field": "#1f9d55", + "nightly_field": "#14532d", + "unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding", + "sizes": "each frame rendered at its own size, never upscaled", + "renderer": renderer, + "generator": "packaging/nightly-icons.py", + }, + "outputs": {name: digest(ICONS / name) for name in outputs}, + "ico_frame_sizes": list(ICO_SIZES), + "icns_png_slots": {kind: size for kind, size in ICNS_SLOTS}, + } + (ICONS / "nightly-provenance.json").write_text(json.dumps(provenance, indent=2) + "\n") + + +def check(): + provenance = json.loads((ICONS / "nightly-provenance.json").read_text()) + ok = True + for name, expected in provenance["outputs"].items(): + actual = digest(ICONS / name) + if actual != expected: + print(f"mismatch: assets/app-icon/{name} is {actual}, provenance says {expected}", file=sys.stderr) + ok = False + ico = (ICONS / "gridcraft-nightly.ico").read_bytes() + count = struct.unpack("I", icns[4:8])[0] != len(icns): + print("mismatch: the ICNS header does not cover the file", file=sys.stderr) + ok = False + return 0 if ok else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--renderer", choices=("auto", "resvg", "chrome"), default="auto") + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + if args.check: + return check() + render_all(args.renderer) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 0000000000..ca9301cbfd --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Nightly source-contract regression tests for GridCraft; local checks, not live API/crypto evidence.""" +import base64 +import copy +import hashlib +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +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"] + +# The Linux leg's public release key, as the protected release checkout must carry it. +LINUX_KEY = ROOT / ".github/nightly-linux-signing-key.asc" + + +def openpgp_primary_fingerprints(armored): + """Return the v4 fingerprint of every primary public-key packet in one armored block. + + A narrow reader for the committed public key, not a general OpenPGP parser: anything other + than one well-formed public-key block, or any secret material, refuses. + """ + lines = armored.strip().splitlines() + if lines[:1] != ["-----BEGIN PGP PUBLIC KEY BLOCK-----"] or lines[-1:] != ["-----END PGP PUBLIC KEY BLOCK-----"]: + raise ValueError("exactly one armored public key block is required") + body = lines[1:-1] + if "" not in body: + raise ValueError("armor header separator missing") + body = body[body.index("") + 1:] + if not body or not body[-1].startswith("="): + raise ValueError("armor checksum missing") + data = base64.b64decode("".join(body[:-1]), validate=True) + fingerprints, offset = [], 0 + while offset < len(data): + header = data[offset] + if not header & 0x80: + raise ValueError("invalid packet header") + if header & 0x40: + tag, offset = header & 0x3F, offset + 1 + first = data[offset] + if first < 192: + length, offset = first, offset + 1 + elif first < 224: + length, offset = ((first - 192) << 8) + data[offset + 1] + 192, offset + 2 + elif first == 255: + length, offset = int.from_bytes(data[offset + 1:offset + 5], "big"), offset + 5 + else: + raise ValueError("partial packet lengths are not a public key") + else: + tag, kind, offset = (header >> 2) & 0x0F, header & 0x03, offset + 1 + if kind == 3: + raise ValueError("indeterminate packet length") + size = 1 << kind + length, offset = int.from_bytes(data[offset:offset + size], "big"), offset + size + packet = data[offset:offset + length] + if len(packet) != length: + raise ValueError("truncated packet") + if tag == 5 or tag == 7: + raise ValueError("secret key material must never be committed") + if tag == 6: + if packet[:1] != b"\x04": + raise ValueError("only v4 primary keys are expected") + fingerprints.append(hashlib.sha1(b"\x99" + length.to_bytes(2, "big") + packet).hexdigest().upper()) + offset += length + return fingerprints + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + 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": "gridcraft-nightly-release", "cancel-in-progress": "false"}: + raise ValueError("nightly serialization must use its stable group and no cancellation") + + +def job_conditions(jobs): + """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" + 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 + + +def producer_platforms(source): + """Read the one producer job's literal platform list; a narrow source guard, not YAML.""" + 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_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: false\n queue: max"), + ("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: gridcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: gridcraft-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_sonar_classifies_only_the_exact_packaging_fixture_runners(self): + source = (ROOT / "sonar-project.properties").read_text() + self.assertEqual(re.findall(r"(?m)^sonar.sources=(.*)$", source), ["."]) + self.assertEqual(re.findall(r"(?m)^sonar.tests=(.*)$", source), ["packaging"]) + inclusions = re.findall(r"(?m)^sonar.test.inclusions=(.*)$", source) + self.assertEqual(len(inclusions), 1) + entries = inclusions[0].split(",") + expected = {"packaging/nightly-tests.py", "packaging/nightly-archive-tests.py", + "packaging/linux/nightly-linux-launch-tests.py", + "packaging/macos/nightly_plist_tests.py", "packaging/macos/nightly_sign_tests.py", + "packaging/windows/nightly-package-tests.ps1", + "packaging/windows/nightly-signing-tests.ps1", "packaging/nightly-release-tests.py"} + self.assertEqual(set(entries), expected, "classify exact fixtures, never production helpers or wildcard scope") + self.assertEqual(len(entries), len(expected), "duplicate fixture classification") + + 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) + + 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/gridcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/gridcraft' && 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) + + +def push_block(source): + """The whole `push:` mapping, blank lines and nested keys included. + + A blank line does not end a YAML mapping, so the block is delimited by indentation rather than + by contiguous non-empty lines; a path filter after a blank line stays visible to the check. + """ + lines = source.splitlines() + for index, line in enumerate(lines): + if re.fullmatch(r" push:.*", line): + block = [] + for follow in lines[index + 1:]: + if follow.strip() and not follow.startswith(" "): + break + block.append(follow) + return "\n".join(block) + return None + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + 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): + expected = {"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"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/gridcraft") + 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; once set, must be a positive int. + if self.policy["producer_workflow_id"] is not None: + self.assertIs(type(self.policy["producer_workflow_id"]), int) + self.assertGreater(self.policy["producer_workflow_id"], 0) + self.assertNotEqual(self.policy["producer_workflow_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_and_trust_anchors_match_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(set(row), {"unsigned_artifact_name", "trust"}) + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}") + self.assertEqual(row["trust"], {field: value}) + + def test_committed_linux_key_is_exactly_the_one_the_policy_trusts(self): + self.assertFalse(LINUX_KEY.is_symlink(), "the key file must be a regular committed file") + armored = LINUX_KEY.read_text(encoding="ascii") + self.assertEqual(armored.count("-----BEGIN PGP"), 1, "exactly one armored block") + self.assertEqual(openpgp_primary_fingerprints(armored), + [self.policy["platforms"]["linux-x86_64"]["trust"]["fingerprint"]], + "exactly one primary key, and it is the release key the policy trusts") + + def test_key_reader_refuses_secret_or_extra_material(self): + armored = LINUX_KEY.read_text(encoding="ascii") + for change in (armored.replace("PUBLIC KEY BLOCK", "PRIVATE KEY BLOCK"), + armored.replace("-----END PGP PUBLIC KEY BLOCK-----\n", ""), + "Comment: extra\n" + armored): + with self.subTest(change=change[:40]), self.assertRaises(ValueError): + openpgp_primary_fingerprints(change) + + 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/gridcraft", "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 = push_block(source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn("branches: [main]", push) + self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "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_a_path_filter_after_a_blank_line_is_still_rejected(self): + workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n" + block = push_block(workflow) + self.assertIsNotNone(block) + self.assertIn("branches: [main]", block) + self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:") + for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"): + with self.subTest(ignored=ignored): + variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored) + self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:", + "a quoted or unquoted filter must not hide behind a blank line") + + 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) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100755 index 0000000000..684239f495 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Run the synthetic nightly packaging suites together; no app build, no signing, no network.""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("gridcraft_archive_suite", "nightly-archive-tests.py"), + ("gridcraft_plist_suite", "macos/nightly_plist_tests.py"), + ("gridcraft_release_dispatch_suite", "nightly-release-tests.py"), + ("gridcraft_mac_sign_suite", "macos/nightly_sign_tests.py"), + ("gridcraft_linux_launch_suite", "linux/nightly-linux-launch-tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, here / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 0000000000..792198589e --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 0000000000..15c6ac9964 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'gridcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'gridcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.gridcraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'GridCraft Nightly' 'GridCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('GridCraft', 'GridCraft 0.23.1 (nightly-v1)'), @('GridCraft Nightly', 'GridCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/gridcraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'gridcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 0000000000..d45a0f83d6 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,83 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:GRIDCRAFT_VERSION = $version +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 0000000000..1d2312d9c3 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,133 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "gridcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "gridcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('gridcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.gridcraft.nightly-v1' + } +} + +# The same source identity the Linux helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (GRIDCRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (GRIDCRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'GridCraft Nightly' -or $VersionOutput -cne "GridCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:GRIDCRAFT_VERSION -or $Version -cne $env:GRIDCRAFT_VERSION) { throw 'nightly-v1 requires explicit GRIDCRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:GRIDCRAFT_BUILD_SHA $env:GRIDCRAFT_BUILD_DATE $Source.Head $Source.Status +# build.rs reads GRIDCRAFT_BUILD_CHANNEL and GRIDCRAFT_VERSION from the environment: that pair is +# what makes this executable the nightly flavor with the prepared identity, and no other. +$oldChannel = $env:GRIDCRAFT_BUILD_CHANNEL +try { + $env:GRIDCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:GRIDCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # Into the directory the archive steps read (`$TargetDir`), not Cargo's default. + cargo build --release --locked -p gridcraft --target $Target --target-dir $TargetDir + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:GRIDCRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:GRIDCRAFT_BUILD_SHA $env:GRIDCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\gridcraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'GridCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'gridcraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('gridcraft.exe' -notin $Names -or 'gridcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 9a1303064a..386dcfebc7 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -50,11 +53,21 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:GRIDCRAFT_BUILD_SHA) { $env:GRIDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:GRIDCRAFT_BUILD_DATE) { $env:GRIDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# A nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:GRIDCRAFT_BUILD_SHA) { $env:GRIDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:GRIDCRAFT_BUILD_DATE) { $env:GRIDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "GridCraft $Version for Windows $Arch ($Target)" +# The nightly channel is its own producer: a GUI-only intermediate for the trusted signing job, never +# this MSI/portable/CLI contract. +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. @@ -83,6 +96,11 @@ foreach ($check in @(@('gridcraft.exe', 2), @('gridcraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +# The nightly flavor has its own identity; shipping it as the stable app would hand a nightly window +# the stable taskbar identity, data folder and update channel (#16335). +if ((Get-Item -LiteralPath (Join-Path $Bin 'gridcraft.exe')).VersionInfo.ProductName -eq 'GridCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 222d5705b2..fe7d9e39c9 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -13,16 +13,28 @@ This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). + Nightly callers require signing with -Required and can check the signing configuration with + -Required -CheckOnly. Compilation uses the separate -CheckBuildEnvironment mode, which never + imports keys. .EXAMPLE pwsh packaging/windows/sign.ps1 dist/gridcraft.exe dist/gridcraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } @@ -44,11 +56,30 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + # Compilation must never see a key: the nightly producer calls this before cargo, and the trusted + # signing job is a separate operation with its own environment. + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -96,6 +127,10 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + # signtool verify alone can pass while the authenticode state is anything but Valid. + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index 4eed7fd86c..5b67372365 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,9 +1,17 @@ sonar.projectKey=storytold_gridcraft sonar.organization=storytold +# `sonar.tests` turns off the CLI's default scope, so `sonar.sources=.` must name the production +# tree explicitly; without it Sonar indexes the packaging fixtures and nothing else (L5). +sonar.sources=. +sonar.tests=packaging +# Only these are test runners: the helpers they exercise stay production code. +sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/linux/nightly-linux-launch-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py + # The region table is one record per locale with the same field names and many shared values # (month names, formats); that repetition is data, not copy-pasted logic. sonar.cpd.exclusions=crates/core/src/region.rs +sonar.coverage.exclusions=packaging/** # githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by # .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned