mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-28 21:49:49 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea23b769a1 | ||
|
|
0b324da562 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408489772,
|
||||
"producer_workflow_id": 429734489,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -34,26 +34,12 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: wordcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment (which trusts release and
|
||||
# nightly-signer) and export keys in its signing step.
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: wordcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -157,9 +157,6 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
|
||||
return Err(format!("the nightly {label} must be a directory"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
@@ -174,56 +171,11 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's exclusive create probe: a file only this process can have made, created and removed.
|
||||
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
@@ -293,8 +245,6 @@ fn validate_for(
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -391,31 +341,6 @@ mod tests {
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -250,8 +250,7 @@ fn side_menu(ui: &mut Ui, band: f32, current: &str, has_document: bool, show_dis
|
||||
.least_width(LeastWidth::SideMenu)
|
||||
.surface(SurfaceKind::Brand)
|
||||
.label(label("File"))
|
||||
// v0.19.1's row pitch (~42 pt against the 38 pt rows): the theme's tight gap between the page rows.
|
||||
.gap(Gap::Tight)
|
||||
.gap(Gap::None)
|
||||
.scroll(Scroll::vertical())
|
||||
.header(move |ui, _| {
|
||||
ui.add_space(band);
|
||||
|
||||
@@ -748,7 +748,7 @@ fn about_stays_at_the_bottom_of_a_side_menu_that_fits() {
|
||||
}
|
||||
|
||||
/// The side menu is production's rail: 200 pt wide (five rail columns, `LeastWidth::SideMenu`), its page rows about
|
||||
/// 38 pt tall a tight gap apart. The footer's links are rows of the same place, so they read in the rail's white ink;
|
||||
/// 38 pt tall one after another. The footer's links are rows of the same place, so they read in the rail's white ink;
|
||||
/// production's were a little shorter (32 pt), which the side menu place has no row for.
|
||||
#[test]
|
||||
fn the_side_menu_rows_are_production_s_rail_rows() {
|
||||
@@ -758,9 +758,7 @@ fn the_side_menu_rows_are_production_s_rail_rows() {
|
||||
// The least width holds in the row beside the page: before, the row gave the menu only its widest name (~123 pt).
|
||||
assert!((190.0..=260.0).contains(&info.width()), "the menu is production's 200 pt rail: {info:?}");
|
||||
assert!((34.0..=44.0).contains(&info.height()), "a page row is a rail row: {info:?}");
|
||||
// v0.19.1's pitch was ~42 pt for 38 pt rows: the rows are a little apart, not touching and not far apart.
|
||||
let gap = recover.min.y - info.max.y;
|
||||
assert!((1.0..=8.0).contains(&gap), "the rows have a small gap between them: {info:?} {recover:?}");
|
||||
assert!((recover.min.y - info.max.y).abs() < 1.0, "the rows follow each other without a gap: {info:?} {recover:?}");
|
||||
assert!(about.height() <= info.height() + 1.0, "the footer link is no taller than a page row: {info:?} {about:?}");
|
||||
}
|
||||
|
||||
|
||||
@@ -716,17 +716,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
|
||||
let mut state = std::mem::take(&mut app.canvas.reading);
|
||||
let source = source::WordPages::new(app, layout, false, None);
|
||||
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
|
||||
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
|
||||
// the page view's side margin in from the edge.
|
||||
let margin = Env::of(ui).tokens.space.inset.page_side;
|
||||
let footer = footer.shrink2(egui::vec2(margin, 0.0));
|
||||
let far = if crate::i18n::current().rtl() {
|
||||
egui::Layout::left_to_right(egui::Align::Center)
|
||||
} else {
|
||||
egui::Layout::right_to_left(egui::Align::Center)
|
||||
};
|
||||
let nav = ui
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(footer).layout(far), |ui| {
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| {
|
||||
ReadingNav::new(&mut state, layout.pages.len()).position(true).action(tl!("Edit Document")).show(ui)
|
||||
})
|
||||
.inner;
|
||||
|
||||
@@ -56,7 +56,7 @@ impl Component for ReadingProbe {
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> egui::Vec2 {
|
||||
let measure = ReadingMeasure::of(TypeRole::Body, |run| cx.layout(run));
|
||||
self.measured = Some(metrics(cx.style.column_gap, cx.style.nav_bar, measure));
|
||||
self.measured = Some(ReadingMetrics::new(cx.style.column_gap, cx.style.nav_bar, measure));
|
||||
egui::Vec2::ZERO
|
||||
}
|
||||
|
||||
@@ -69,19 +69,6 @@ impl Component for ReadingProbe {
|
||||
}
|
||||
}
|
||||
|
||||
/// Column widths Read Mode has always used (about one column per 295 screen points, none under 192), as v0.19.1 laid out 4
|
||||
/// columns at 1440 screen points. craft's body-text measure (66 characters) gives 2 there, so only the gaps come from it.
|
||||
const COLUMN_TARGET: f32 = 295.0;
|
||||
const COLUMN_MIN: f32 = 192.0;
|
||||
|
||||
fn metrics(column_gap: f32, nav_bar: f32, measure: ReadingMeasure) -> ReadingMetrics {
|
||||
let mut m = ReadingMetrics::new(column_gap, nav_bar, measure);
|
||||
// lean: fixed px, not the text size; follow the body text again if Read Mode should scale with it.
|
||||
m.column_target = COLUMN_TARGET;
|
||||
m.column_min = COLUMN_MIN;
|
||||
m
|
||||
}
|
||||
|
||||
/// The reading metrics under the current theme, or `None` when the probe did not measure this pass.
|
||||
pub(super) fn read(ui: &mut Ui) -> Option<ReadingMetrics> {
|
||||
ReadingProbe { common: Common::new(), measured: None }.label("Reading metrics").show(ui).metrics
|
||||
|
||||
@@ -253,48 +253,6 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
|
||||
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
|
||||
}
|
||||
|
||||
/// #8019: at 1440 x 900 Read Mode lays out several narrow columns (v0.19.1: 4), not the two the body
|
||||
/// text's measure gave after the port.
|
||||
#[test]
|
||||
fn read_mode_lays_out_several_columns_at_1440() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("view.readMode", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let px = ReadingView::screen_scale(1.0) * h.state().session.view.read_width;
|
||||
assert!(px > 0.0 && 4.0 * px < 1440.0, "columns {px} px wide: four do not fit");
|
||||
}
|
||||
|
||||
/// #8019: the page-turn row (position and Edit Document) sits in the bottom-right quadrant, as in v0.19.1,
|
||||
/// not at the bottom left where craft's row starts.
|
||||
#[test]
|
||||
fn read_mode_pager_is_at_the_bottom_right() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("view.readMode", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
|
||||
for label in ["Edit Document", "1 / 1"] {
|
||||
let r = h.get_all_by_label(label).last().unwrap().rect();
|
||||
assert!(r.center().x > screen.center().x && r.center().y > screen.center().y, "{label} at {r:?}: not bottom right");
|
||||
}
|
||||
}
|
||||
|
||||
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
|
||||
/// there is no caret, so the page's draw list isn't built for it.
|
||||
#[test]
|
||||
|
||||
@@ -39,13 +39,6 @@ pub(crate) use host::close_all;
|
||||
pub(crate) use mailings::{FilterRow, RecipientDraft, RecipientFilter, RecipientListDialog, hold_rows, merge_order, visible_recipients};
|
||||
pub(crate) use page_setup::PAPER_LABELS;
|
||||
|
||||
/// `max_rows` for a `TileGrid` that shows `rows` rows of `columns` tiles. The collection counts the cap in
|
||||
/// items (the tile `rows` in, not the grid row it is in), so a cap of `rows` shows one row; a cap past the item
|
||||
/// count adds blank rows, so it stops at `len`. lean: upstream fix in craft-libs `rows_height`, then drop this.
|
||||
pub(crate) fn tile_rows_cap(len: usize, columns: usize, rows: usize) -> u16 {
|
||||
u16::try_from(len.min(columns * rows)).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
/// Opens the dialog `name` for a script, a button or a command, with `params`; the module of the name reads what it
|
||||
/// needs of them. Returns the dialog's id, or `None` when no dialog opened (an unknown name, nothing to show, or a
|
||||
/// pane such as Restrict Editing).
|
||||
|
||||
@@ -3,25 +3,23 @@ use std::sync::Arc;
|
||||
use craft::behavior::{ColumnWidth, Selection, SelectionChange, keyed};
|
||||
use craft::font_manager::Catalog;
|
||||
use craft::font_manager::picker::FontPickerSettings;
|
||||
use craft::theme::Mode;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, ColumnKey, ColumnSpec, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, ColumnKey, ColumnSpec, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Kbd, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
|
||||
use craft::ui::patterns::form_dialogs::{FormCx, FormDialog};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::{Env, Label};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::table::Table;
|
||||
use craft::ui::tabs::{Tab, TabKind, TabStrip};
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::Ui;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{select_index, settled, word};
|
||||
use super::{select_index, settled, text_field, word};
|
||||
use crate::WordApp;
|
||||
use crate::dialogs::host::{DialogHooks, Settle, open_with};
|
||||
use crate::widgets::font_box::font_picker;
|
||||
@@ -38,12 +36,6 @@ pub struct RecentSymbol {
|
||||
pub font: String,
|
||||
}
|
||||
|
||||
/// Characters per row of the Symbols map (Word's grid is 16 wide).
|
||||
// lean: the cap assumes this many columns; read the laid-out count if the map becomes resizable.
|
||||
const GRID_COLUMNS: usize = 16;
|
||||
/// Rows of the Symbols map shown before it scrolls.
|
||||
const GRID_ROWS: usize = 8;
|
||||
|
||||
/// How many recent symbols are kept.
|
||||
pub const RECENT_SYMBOLS: usize = 20;
|
||||
|
||||
@@ -622,21 +614,14 @@ fn symbol_page(ui: &mut Ui, form: &mut SymbolForm, catalog: Option<&Arc<Catalog>
|
||||
{
|
||||
form.jump_to(name);
|
||||
}
|
||||
// The theme's mode, not egui's `dark_mode`, which the craft theme does not drive (light tiles in the light theme, #8021).
|
||||
let dark = Env::of(ui).view().mode() == Mode::Dark;
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let activated = glyph_grid(ui, form, dark);
|
||||
recent_row(ui, form, dark);
|
||||
if let Some(c) = form.selected {
|
||||
Text::new(Label::from(format!("U+{:04X}", c as u32))).show(ui);
|
||||
}
|
||||
let before = form.code.clone();
|
||||
let label = word("Character code:");
|
||||
Field::new(label.clone()).id_salt("symbol_code").show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
TextField::new(label.clone(), Bind::bound(&mut form.code)).show(ui);
|
||||
Text::new(word("from Unicode (hex)")).show(ui);
|
||||
});
|
||||
});
|
||||
text_field(ui, "symbol_code", &word("Character code:"), &mut form.code);
|
||||
if form.code != before {
|
||||
let code = form.code.clone();
|
||||
form.select_code(&code);
|
||||
@@ -646,17 +631,14 @@ fn symbol_page(ui: &mut Ui, form: &mut SymbolForm, catalog: Option<&Arc<Catalog>
|
||||
|
||||
/// The recently inserted symbols as one row of glyphs, each in its own font; a click picks one.
|
||||
fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
|
||||
// The heading shows while the row is empty too, as Word does; with symbols it labels the row.
|
||||
if form.recent.is_empty() {
|
||||
Text::new(word("Recently used symbols:")).show(ui);
|
||||
return;
|
||||
}
|
||||
let positions: Vec<usize> = (0..form.recent.len()).collect();
|
||||
let source = keyed(&positions, |at: &usize| *at);
|
||||
let mut events = Vec::new();
|
||||
Field::new(word("Recently used symbols:")).show(ui, |ui, _| {
|
||||
let events = {
|
||||
let recent = &form.recent;
|
||||
events = TileGrid::new(word("Recently used symbols:"))
|
||||
TileGrid::new(word("Recently used symbols:"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.caption(CaptionPlace::None)
|
||||
@@ -670,8 +652,8 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
|
||||
Tile::new(r.ch).thumb(ThumbAspect::SQUARE, move |cx, rect| paint_glyph(cx, rect, ch, &font, dark))
|
||||
})
|
||||
.response
|
||||
.events;
|
||||
});
|
||||
.events
|
||||
};
|
||||
for event in events {
|
||||
if let CollectionEvent::Selection { change: SelectionChange::Set(rows), .. } = event
|
||||
&& let Some(r) = rows.last().and_then(|i| form.recent.get(*i)).cloned()
|
||||
@@ -703,8 +685,7 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
let mut grid = TileGrid::new(word("Symbols"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.max_rows(crate::dialogs::tile_rows_cap(form.chars.len(), GRID_COLUMNS, GRID_ROWS))
|
||||
.card_columns(GRID_COLUMNS)
|
||||
.max_rows(8)
|
||||
.caption(CaptionPlace::None)
|
||||
.selection(Bind::bound(&mut selection));
|
||||
if let Some(at) = reveal {
|
||||
|
||||
@@ -138,43 +138,6 @@ fn symbol_dialog_uses_compact_tile_grids() {
|
||||
assert!(recent.height() < 80.0, "recently used symbols row should be compact: {}", recent.height());
|
||||
}
|
||||
|
||||
fn h_recent(a: &mut WordApp) {
|
||||
remember_symbol(a, "©", "DejaVu Sans");
|
||||
}
|
||||
|
||||
/// #7972: the Symbols map shows rows of characters (not one strip), with the Recently used heading
|
||||
/// and the note that the code is Unicode hex.
|
||||
#[test]
|
||||
fn symbol_dialog_shows_the_map_in_rows() {
|
||||
use egui::accesskit::Role;
|
||||
let mut a = app();
|
||||
h_recent(&mut a);
|
||||
let mut h = testing::harness(a);
|
||||
crate::dialogs::open(h.state_mut(), "symbol", &json!({})).expect("symbol dialog opens");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.query_all_by_label("Recently used symbols:").count(), 1, "the heading is the row's one name");
|
||||
h.get_by_role_and_label(Role::ListBox, "Recently used symbols:");
|
||||
let map = h.get_by_role_and_label(Role::ListBox, "Symbols").rect();
|
||||
let tile = h.query_all_by_label("A").map(|n| n.rect()).find(|r| map.contains_rect(*r)).expect("a tile in the map");
|
||||
assert!(map.height() > 3.0 * tile.height(), "the map is several rows tall: {} vs a tile {}", map.height(), tile.height());
|
||||
h.get_by_label("from Unicode (hex)");
|
||||
}
|
||||
|
||||
/// #7973: Insert Diagram offers every layout in its grid, not the first row of three.
|
||||
#[test]
|
||||
fn insert_diagram_dialog_shows_every_layout() {
|
||||
use egui::accesskit::Role;
|
||||
let mut h = testing::harness(app());
|
||||
crate::dialogs::open(h.state_mut(), "insertSmartArt", &json!({})).expect("the dialog opens");
|
||||
// The tiles' heights settle over a few passes.
|
||||
h.run_steps(10);
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Layouts").rect();
|
||||
for layout in wordcraft_doc::smart_art::SmartArtLayout::ALL {
|
||||
let shown = h.query_all_by_label(layout.label()).any(|n| grid.contains(n.rect().center()));
|
||||
assert!(shown, "{} is shown in the grid", layout.label());
|
||||
}
|
||||
}
|
||||
|
||||
/// The Field dialog builds the field code from its options.
|
||||
#[test]
|
||||
fn field_dialog_builds_the_instruction() {
|
||||
|
||||
@@ -321,7 +321,7 @@ fn layout_tiles(ui: &mut Ui, theme: &[Rgb], form: &mut SmartArtForm) -> bool {
|
||||
.card_columns(3)
|
||||
// Production's picker is three tile rows high and scrolls the rest; the cap also makes the grid the one owner
|
||||
// of its scroll inside the dialog's scrolling body.
|
||||
.max_rows(crate::dialogs::tile_rows_cap(shown.len(), 3, 3))
|
||||
.max_rows(3)
|
||||
.selection(Bind::given(Selection::single(current)))
|
||||
.show_items(ui, &keyed(&positions, |i| *i), &mut |key, _| {
|
||||
let layout = shown.get(*key).copied().unwrap_or_default();
|
||||
|
||||
@@ -3,21 +3,18 @@
|
||||
//! `styles.copyFrom`, `styles.delete`, `styles.rename`), so agents get the same result without
|
||||
//! the dialogs.
|
||||
|
||||
use craft::behavior::{ColumnWidth, EditEvent, Selection, SelectionChange, item_source::keyed};
|
||||
use craft::behavior::{EditEvent, Selection, SelectionChange, item_source::keyed};
|
||||
use craft::host::PickRequest;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Stack};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{List, ListRow};
|
||||
use craft::ui::notices::Notice;
|
||||
use craft::ui::patterns::form_dialogs::{FormCx, PathRow};
|
||||
use craft::ui::runtime::env::{Env, Label};
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::style::SurfaceKind;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -27,15 +24,6 @@ use super::styles::{action, label};
|
||||
use crate::WordApp;
|
||||
|
||||
const ORGANIZER_KEY: &str = "organizer";
|
||||
/// The Organizer's columns: each takes what it holds, and a list holds at least `LIST_WIDTH` (a fill column takes no more
|
||||
/// than its content in a dialog that sizes to its content, so an empty list was a few pixels wide).
|
||||
const COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content; 3];
|
||||
/// The least width of a list, in points.
|
||||
const LIST_WIDTH: f32 = 200.0;
|
||||
/// The rows each list shows before it scrolls.
|
||||
const LIST_ROWS: u16 = 12;
|
||||
/// The other file's list has its name above it, so it shows one row fewer to end level with the first.
|
||||
const OTHER_ROWS: u16 = LIST_ROWS - 1;
|
||||
|
||||
/// The Templates and Add-ins dialog's fields.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -248,69 +236,50 @@ impl OrganizerDialog {
|
||||
|
||||
fn body(&mut self, ui: &mut Ui) {
|
||||
let reason = browse_reason(ui);
|
||||
let mine_id = ui.scope_id().with("organizer_mine");
|
||||
// Three columns as the old dialog had: this document's styles, Copy / Delete / Rename, the other file's styles.
|
||||
Grid::new(&COLUMNS).cells(CellAlign::Top).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
ui.set_min_width(LIST_WIDTH);
|
||||
let mut selection = Selection::single(self.left.clone());
|
||||
let mine = &self.mine;
|
||||
let source = keyed(mine, |st| text_of(st, "id"));
|
||||
let out = List::new(label(tl!("Document")))
|
||||
.surface(SurfaceKind::Frame)
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.rename(true)
|
||||
.can_rename(|key: &String| {
|
||||
mine.iter().find(|x| text_of(x, "id") == *key).is_some_and(|x| !x.get("builtIn").and_then(Value::as_bool).unwrap_or(true))
|
||||
})
|
||||
.id(mine_id)
|
||||
.min_rows(LIST_ROWS)
|
||||
.max_rows(LIST_ROWS)
|
||||
.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some(st) = mine.get(icx.at) else { return ListRow::spacer() };
|
||||
ListRow::new(label(text_of(st, "name"))).lead_text(label(glyph(&text_of(st, "type"))), label("¶"))
|
||||
});
|
||||
for event in out.events {
|
||||
match event {
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
|
||||
if let Some(key) = keys.last() {
|
||||
self.left = key.clone();
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let mut selection = Selection::single(self.left.clone());
|
||||
let mine = &self.mine;
|
||||
let source = keyed(mine, |st| text_of(st, "id"));
|
||||
let out = List::new(label(tl!("Document")))
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.rename(true)
|
||||
.can_rename(|key: &String| {
|
||||
mine.iter().find(|x| text_of(x, "id") == *key).is_some_and(|x| !x.get("builtIn").and_then(Value::as_bool).unwrap_or(true))
|
||||
})
|
||||
.id_salt("mine")
|
||||
.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some(st) = mine.get(icx.at) else { return ListRow::spacer() };
|
||||
ListRow::new(label(text_of(st, "name"))).lead_text(label(glyph(&text_of(st, "type"))), label("¶"))
|
||||
});
|
||||
for event in out.events {
|
||||
match event {
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
|
||||
if let Some(key) = keys.last() {
|
||||
self.left = key.clone();
|
||||
}
|
||||
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => {
|
||||
self.requests.push(Request::Rename { style: after.key, name: after.name });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => {
|
||||
self.requests.push(Request::Rename { style: after.key, name: after.name });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if action(ui, "copy", label(tl!("Copy")), !self.right.is_empty(), None) {
|
||||
self.requests.push(Request::Copy);
|
||||
}
|
||||
if action(ui, "delete", label(tl!("Delete")), !self.left_builtin(), None) {
|
||||
self.requests.push(Request::Delete(self.left.clone()));
|
||||
}
|
||||
// The list's own rename field takes the name in place.
|
||||
if action(ui, "rename", label(tl!("Rename…")), !self.left_builtin(), None) {
|
||||
request_rename(ui.ctx(), mine_id, &self.left);
|
||||
}
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
ui.set_min_width(LIST_WIDTH);
|
||||
let name = std::path::Path::new(&self.file).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "—".into());
|
||||
Text::new(label(name)).show(ui);
|
||||
}
|
||||
if action(ui, "copy", label(tl!("Copy")), !self.right.is_empty(), None) {
|
||||
self.requests.push(Request::Copy);
|
||||
}
|
||||
if action(ui, "delete", label(tl!("Delete")), !self.left_builtin(), None) {
|
||||
self.requests.push(Request::Delete(self.left.clone()));
|
||||
}
|
||||
let name = std::path::Path::new(&self.file).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "—".into());
|
||||
Field::new(label(name)).show(ui, |ui, _| {
|
||||
let mut selection = Selection::single(self.right.clone());
|
||||
let other = &self.other;
|
||||
let source = keyed(other, |(n, _)| n.clone());
|
||||
let out = List::new(label(tl!("Template")))
|
||||
.surface(SurfaceKind::Frame)
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.id_salt("other")
|
||||
.min_rows(OTHER_ROWS)
|
||||
.max_rows(OTHER_ROWS)
|
||||
.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some((n, ty)) = other.get(icx.at) else { return ListRow::spacer() };
|
||||
ListRow::new(label(n)).lead_text(label(glyph(ty)), label("¶"))
|
||||
@@ -322,13 +291,12 @@ impl OrganizerDialog {
|
||||
self.right = key.clone();
|
||||
}
|
||||
}
|
||||
let picked = template_row(label(tl!("Template")), Bind::bound(&mut self.file), reason.clone()).show(ui).picked;
|
||||
if let Some(path) = picked {
|
||||
self.requests.push(Request::Load(path));
|
||||
}
|
||||
});
|
||||
});
|
||||
// The other file's path and Browse stand under both lists, at the dialog's full width.
|
||||
let picked = template_row(label(tl!("Template")), Bind::bound(&mut self.file), reason.clone()).show(ui).picked;
|
||||
if let Some(path) = picked {
|
||||
self.requests.push(Request::Load(path));
|
||||
}
|
||||
if !self.message.is_empty() {
|
||||
Notice::new(craft::theme::variant::Tone::Bad, label(&self.message)).show(ui);
|
||||
}
|
||||
|
||||
@@ -191,11 +191,11 @@ const MARGIN_SIDES: [(&str, &str); 4] = [("top", "Top"), ("left", "Left"), ("bot
|
||||
fn open_cell_margins(app: &mut WordApp, ctx: &Context, parent: Option<DialogId>) -> Option<DialogId> {
|
||||
let margins = cell_margins_pt(app)?;
|
||||
let fields = DialogFields::from_pairs(MARGIN_SIDES.iter().zip(margins).map(|((key, _), v)| (*key, v)));
|
||||
let units = crate::options::lengths(app.session.units());
|
||||
let kind = crate::options::unit_kind(app.session.units());
|
||||
let dialog = HostedParamDialog::new(ctx, "tableCellMargins", fields, move |fields| {
|
||||
let params: Vec<Param> = MARGIN_SIDES
|
||||
.iter()
|
||||
.map(|(key, label)| Param::number(*key, tl!(label).to_string(), 0.0, units.shown.step(), 2).bounds(Some(0.0), Some(144.0)).length(units))
|
||||
.map(|(key, label)| Param::number(*key, tl!(label).to_string(), 0.0, 1.0, 2).bounds(Some(0.0), Some(144.0)).unit(kind))
|
||||
.collect();
|
||||
ParamDialog::command("tableCellMargins", tl!("Cell Margins").to_string(), params).values(Bind::bound(fields)).alt_resets(false)
|
||||
});
|
||||
|
||||
@@ -2283,109 +2283,3 @@ fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_out
|
||||
let key2 = chrome::nudge_id(&h.ctx, id2);
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key2)).is_none(), "reopened dialog starts still");
|
||||
}
|
||||
|
||||
/// #7970: Cell Margins shows the table's points in the interface unit (0.19 cm, not 5.4 cm), and OK without
|
||||
/// an edit leaves the table's margins as they were.
|
||||
#[test]
|
||||
fn cell_margins_dialog_shows_points_in_the_interface_unit_and_ok_changes_nothing() {
|
||||
let mut app = app_with("");
|
||||
let _ = app.run("insert.table", json!({"rows": 1, "cols": 1}));
|
||||
app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters);
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
let (tp, _, _) = h.state().session.sel.focus.path.cell().unwrap();
|
||||
let margins =
|
||||
|h: &egui_kittest::Harness<'_, WordApp>| h.state().session.doc.table(h.state().session.sel.focus.story, &tp).unwrap().props.cell_margins;
|
||||
let before = margins(&h);
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "tableCellMargins"}));
|
||||
h.run_steps(3);
|
||||
let left = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Left").value().unwrap_or_default();
|
||||
let shown: f64 = left.trim_end_matches(|c: char| !c.is_ascii_digit()).replace(',', ".").parse().unwrap_or(f64::NAN);
|
||||
assert!(shown < 1.0, "5.4 pt is about 0.19 cm, not the point count: {left:?}");
|
||||
let id = id_of(h.state(), "tableCellMargins");
|
||||
let ctx = h.ctx.clone();
|
||||
let _ = h.state_mut().dialog_host.confirm_by_id(&ctx, id);
|
||||
h.run_steps(4);
|
||||
assert_eq!(margins(&h), before, "OK without an edit writes no margins");
|
||||
}
|
||||
|
||||
/// #7970: a width typed into Cell Margins in the interface unit reaches the table in points (1 cm is about 28 pt).
|
||||
#[test]
|
||||
fn cell_margins_dialog_converts_a_typed_length_back_to_points() {
|
||||
let mut app = app_with("");
|
||||
let _ = app.run("insert.table", json!({"rows": 1, "cols": 1}));
|
||||
app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters);
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
let (tp, _, _) = h.state().session.sel.focus.path.cell().unwrap();
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "tableCellMargins"}));
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Left").click();
|
||||
h.run_steps(3);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
h.event(egui::Event::Paste("1".into()));
|
||||
h.run_steps(3);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(3);
|
||||
let id = id_of(h.state(), "tableCellMargins");
|
||||
let ctx = h.ctx.clone();
|
||||
let _ = h.state_mut().dialog_host.confirm_by_id(&ctx, id);
|
||||
h.run_steps(4);
|
||||
let left = h.state().session.doc.table(h.state().session.sel.focus.story, &tp).unwrap().props.cell_margins.map(|m| m[1]);
|
||||
assert!(left.is_some_and(|l| (l - 28.35).abs() < 0.5), "1 cm is about 28.35 pt: {left:?}");
|
||||
}
|
||||
|
||||
/// #7980: the Organizer shows this document's styles and the other file's side by side, with Copy, Delete and
|
||||
/// Rename between them, all inside the dialog.
|
||||
#[test]
|
||||
fn organizer_shows_both_lists_and_its_buttons() {
|
||||
use egui::accesskit::Role;
|
||||
let mut h = app_harness(app_with(""));
|
||||
h.run_steps(2);
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "organizer"}));
|
||||
h.run_steps(4);
|
||||
let rect = |h: &egui_kittest::Harness<'_, WordApp>, role, name: &str| h.get_by_role_and_label(role, name).rect();
|
||||
let mine = rect(&h, Role::List, "Document");
|
||||
let other = rect(&h, Role::List, "Template");
|
||||
assert!(mine.is_positive() && other.is_positive() && mine.right() <= other.left(), "the lists stand side by side: {mine:?} {other:?}");
|
||||
// Each list is wider than the button column between them, empty (no other file) or not.
|
||||
let rename = rect(&h, Role::Button, "Rename…");
|
||||
assert!(mine.width() > rename.width() && other.width() > rename.width(), "the lists are wider than the buttons: {mine:?} {other:?} {rename:?}");
|
||||
// The ribbon has its own Copy: the one that counts stands between the lists.
|
||||
for name in ["Copy", "Delete", "Rename…"] {
|
||||
let between = h
|
||||
.query_all(egui_kittest::kittest::By::new().role(Role::Button).label(name))
|
||||
.any(|b| b.rect().left() >= mine.right() - 1.0 && b.rect().right() <= other.left() + 1.0);
|
||||
assert!(between, "{name} stands between the lists {mine:?} {other:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Part of #7980: the Organizer's two lists have a visible frame, as before the port; without it an empty list is a
|
||||
/// blank patch.
|
||||
#[test]
|
||||
fn the_organizer_lists_are_framed() {
|
||||
use egui::accesskit::Role;
|
||||
fn rects<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::epaint::RectShape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(inner) => inner.iter().for_each(|s| rects(s, out)),
|
||||
egui::Shape::Rect(r) => out.push(r),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = app_harness(app_with(""));
|
||||
h.run_steps(2);
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "organizer"}));
|
||||
h.run_steps(4);
|
||||
let mut seen = Vec::new();
|
||||
h.output().shapes.iter().for_each(|c| rects(&c.shape, &mut seen));
|
||||
for label in ["Document", "Template"] {
|
||||
let list = h.get_by_role_and_label(Role::List, label).rect();
|
||||
assert!(
|
||||
seen.iter().any(|r| r.stroke.width > 0.0
|
||||
&& r.stroke.color.a() > 0
|
||||
&& r.rect.contains_rect(list.shrink(2.0))
|
||||
&& list.expand(2.0).contains_rect(r.rect)),
|
||||
"the list {label:?} {list:?} has a border"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ use wordcraft_doc::math::{MNode, MRun, parse_linear};
|
||||
use wordcraft_engine::math_gallery::{BUILT_INS, STRUCTURES, SYMBOL_SETS};
|
||||
|
||||
use crate::WordApp;
|
||||
use crate::previews::{MathSource, math_key, math_painter, math_picture, math_thumbnails};
|
||||
use crate::previews::{MathSource, math_key, math_picture, math_thumbnails};
|
||||
use crate::ribbon::common::menu_button;
|
||||
|
||||
/// What each structure button shows.
|
||||
@@ -44,8 +44,7 @@ pub(crate) fn button_picture(id: &str) -> &'static str {
|
||||
|
||||
/// The ink math pictures are rendered in: the theme's text colour.
|
||||
fn ink(ui: &Ui) -> Color32 {
|
||||
// The craft theme's token, not egui's visuals, which the craft theme does not drive (grey ink in the light theme, #7975).
|
||||
craft::ui::style::rgba_color(craft::ui::runtime::env::Env::of(ui).tokens.color.text.normal)
|
||||
ui.visuals().text_color()
|
||||
}
|
||||
|
||||
/// The keys `0..n` as a collection source.
|
||||
@@ -155,14 +154,10 @@ fn math_menu_button(ui: &mut Ui, picture: &str, label: &str, body: impl FnMut(&m
|
||||
let _ = menu_button(ui, face, tl!(label).to_string(), None, body);
|
||||
}
|
||||
|
||||
/// The size a symbol is set at. The strip's tiles are 24 pt wide and the picture is fitted to them, so it reads at
|
||||
/// about 16 pt (11 pt drew a speck).
|
||||
const SYMBOL_PT: f32 = 22.0;
|
||||
|
||||
/// The picture source of one symbol, as a literal run.
|
||||
pub(crate) fn symbol_source(c: char, ink: Color32) -> MathSource {
|
||||
fn symbol_source(c: char, ink: Color32) -> MathSource {
|
||||
let nodes = vec![MNode::Run(MRun { text: c.to_string(), lit: true, ..Default::default() })];
|
||||
MathSource::new(nodes, false, SYMBOL_PT, [1, 1], ink).fitted()
|
||||
MathSource::new(nodes, false, 11.0, [1, 1], ink)
|
||||
}
|
||||
|
||||
/// A grid of rendered math tiles, `(name, picture key)` each over its own source, shaped as the sources are;
|
||||
@@ -226,14 +221,13 @@ fn symbols(ui: &mut Ui, app: &mut WordApp) {
|
||||
let ink = ink(ui);
|
||||
let thumbs = math_thumbnails(ui.ctx());
|
||||
let sources: Vec<MathSource> = all.iter().map(|c| symbol_source(*c, ink)).collect();
|
||||
let painters: Vec<_> = all.iter().zip(&sources).map(|(c, source)| math_painter(math_key(&format!("sym:{c}")), &thumbs, source)).collect();
|
||||
let items: Vec<GalleryItem<'_, char>> = all
|
||||
.iter()
|
||||
.zip(&painters)
|
||||
.map(|(c, paint)| GalleryItem {
|
||||
.zip(&sources)
|
||||
.map(|(c, source)| GalleryItem {
|
||||
key: *c,
|
||||
label: Label::from(symbol_tooltip(*c, &math_placeholder(ui, &c.to_string()))),
|
||||
face: GalleryFace::Paint(paint),
|
||||
face: GalleryFace::rendered(math_key(&format!("sym:{c}")), &thumbs, source),
|
||||
})
|
||||
.collect();
|
||||
let mut sets = |ui: &mut Ui| {
|
||||
@@ -392,21 +386,6 @@ mod placeholder_tests {
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// The pictures' ink is the craft theme's text colour, so it reads against the window in the light theme (egui's
|
||||
/// own visuals are not driven by the craft theme and gave grey ink there, #7975).
|
||||
#[test]
|
||||
fn the_equation_ink_contrasts_with_the_theme_surface() {
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let env = craft::ui::runtime::env::Env::of(ui);
|
||||
let luma = |c: egui::Color32| 0.299 * f32::from(c.r()) + 0.587 * f32::from(c.g()) + 0.114 * f32::from(c.b());
|
||||
let ink = super::ink(ui);
|
||||
let surface = craft::ui::style::rgba_color(env.tokens.color.surface.background);
|
||||
assert!((luma(ink) - luma(surface)).abs() > 100.0, "ink {ink:?} against {surface:?}");
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_math_glyph_falls_back_to_its_linear_name() {
|
||||
// Without craft-fonts the interface fonts may have no `┬`: the Equation button's picture
|
||||
|
||||
@@ -10,10 +10,7 @@ use std::sync::Arc;
|
||||
use craft::theme::Mode;
|
||||
use craft::ui::display::Picture;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::primitives::textures::{
|
||||
LoadedPicture, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails,
|
||||
};
|
||||
use craft::ui::primitives::textures::{LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use egui::{Color32, ColorImage, Vec2};
|
||||
use wordcraft_doc::props::CharProps;
|
||||
@@ -166,37 +163,19 @@ pub(crate) fn dim(img: &mut ColorImage) {
|
||||
|
||||
/// Renders an equation off the frame for [`math_picture`]: the inputs of one tile, owned so the render job
|
||||
/// can run on a queue lane.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct MathSource {
|
||||
nodes: Arc<wordcraft_doc::math::Arg>,
|
||||
display: bool,
|
||||
pt: f32,
|
||||
aspect: [u16; 2],
|
||||
ink: Color32,
|
||||
/// Shrink `pt` until the ink clears the picture's edges (symbols of any width, in any font).
|
||||
fit: bool,
|
||||
}
|
||||
|
||||
impl MathSource {
|
||||
/// An equation of `nodes` (`display` style, font size `pt`) for a picture `aspect[0]` wide to `aspect[1]` high,
|
||||
/// inked `ink`. The picture is an ink mask baked in `ink`, so the theme's text colour is part of its revision.
|
||||
pub(crate) fn new(nodes: wordcraft_doc::math::Arg, display: bool, pt: f32, aspect: [u16; 2], ink: Color32) -> Self {
|
||||
MathSource { nodes: Arc::new(nodes), display, pt, aspect, ink, fit: false }
|
||||
}
|
||||
|
||||
/// This source, its size cut down where its ink would reach the picture's edge.
|
||||
pub(crate) fn fitted(mut self) -> Self {
|
||||
self.fit = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The picture for a `w`×`h` pt box at `ppp`, fitted when asked.
|
||||
pub(crate) fn image(&self, w: f32, h: f32, ppp: f32) -> Option<ColorImage> {
|
||||
if self.fit {
|
||||
math_image_fitted(&self.nodes, self.display, self.pt, w, h, ppp)
|
||||
} else {
|
||||
math_image(&self.nodes, self.display, self.pt, w, h, ppp)
|
||||
}
|
||||
MathSource { nodes: Arc::new(nodes), display, pt, aspect, ink }
|
||||
}
|
||||
|
||||
/// The shape the tile or button shows the picture in.
|
||||
@@ -220,9 +199,10 @@ impl ThumbSource<u64> for MathSource {
|
||||
}
|
||||
|
||||
fn render(&self, _key: &u64, request: &ThumbRequest) -> ThumbRender {
|
||||
let (source, size, ink, ppp) = (self.clone(), self.size_for(request), self.ink, request.pixels_per_point);
|
||||
let (nodes, display, pt, size, ink, ppp) =
|
||||
(Arc::clone(&self.nodes), self.display, self.pt, self.size_for(request), self.ink, request.pixels_per_point);
|
||||
ThumbRender::Later(Box::new(move |_| {
|
||||
Ok(match source.image(size.x, size.y, ppp) {
|
||||
Ok(match math_image(&nodes, display, pt, size.x, size.y, ppp) {
|
||||
Some(mut img) => {
|
||||
for p in &mut img.pixels {
|
||||
*p = Color32::from_rgba_unmultiplied(ink.r(), ink.g(), ink.b(), p.a());
|
||||
@@ -245,47 +225,9 @@ pub(crate) fn math_thumbnails(ctx: &egui::Context) -> Thumbnails<u64> {
|
||||
Thumbnails::in_context(ctx, "wordcraft.math", ThumbnailOptions::new())
|
||||
}
|
||||
|
||||
/// The picture request for a tile `rect`: sized by its short side. The picture is fitted into the rect, so a
|
||||
/// request from the long side of a tall tile (24 x 52 pt in the ribbon) shrinks the symbol to a speck.
|
||||
pub(crate) fn cell_request(rect: egui::Rect, pixels_per_point: f32) -> ThumbRequest {
|
||||
ThumbRequest::for_cell(rect.width().min(rect.height()), pixels_per_point)
|
||||
}
|
||||
|
||||
/// Paints the equation picture `key` in a rect, asked for at the size it is painted, for a `GalleryFace::Paint`. The
|
||||
/// picture is an ink mask, so it is drawn without the transparency grid; the store's placeholder shows until the render
|
||||
/// lands. lean: only `GalleryFace::rendered` lacks `Picture`'s `checker(false)`; drop this once it has one.
|
||||
pub(crate) fn math_painter<'a>(key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a MathSource) -> impl Fn(&ContentPainterCx, egui::Rect) + 'a {
|
||||
move |cx, rect| {
|
||||
let request = cell_request(rect, cx.pixels_per_point());
|
||||
let state = thumbnails.state(cx.painter.ctx(), source, &key, &request, Priority::VISIBLE);
|
||||
thumbnails.paint(cx, rect, &state, &ThumbPaint::default().checker(false));
|
||||
}
|
||||
}
|
||||
|
||||
/// An equation picture that shows the framework's placeholder until the render lands.
|
||||
pub(crate) fn math_picture<'a>(label: impl Into<Label>, key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a MathSource) -> Picture<'a> {
|
||||
Picture::rendered(label, key, thumbnails, source).checker(false)
|
||||
}
|
||||
|
||||
/// [`math_image`], redrawn smaller while the ink reaches within a margin of the picture's edge, so a glyph
|
||||
/// wider than the tile in this platform's font is shrunk to fit and narrow ones keep `pt`. Measured, not assumed.
|
||||
fn math_image_fitted(nodes: &wordcraft_doc::math::Arg, display: bool, pt: f32, w: f32, h: f32, ppp: f32) -> Option<ColorImage> {
|
||||
let mut pt = pt;
|
||||
let mut img = math_image(nodes, display, pt, w, h, ppp)?;
|
||||
for _ in 0..4 {
|
||||
let [iw, ih] = img.size;
|
||||
let margin = (iw / 16).max(2);
|
||||
let cols: Vec<usize> = (0..iw).filter(|x| (0..ih).any(|y| img.pixels[y * iw + x].a() > 64)).collect();
|
||||
let (Some(lo), Some(hi)) = (cols.first().copied(), cols.last().copied()) else { break };
|
||||
if lo >= margin && hi + margin < iw {
|
||||
break;
|
||||
}
|
||||
// Clipped ink under-measures, so always step down by at least a tenth.
|
||||
let room = iw.saturating_sub(2 * margin) as f32 / (hi - lo + 1) as f32;
|
||||
pt *= room.min(0.9);
|
||||
img = math_image(nodes, display, pt, w, h, ppp)?;
|
||||
}
|
||||
Some(img)
|
||||
Picture::rendered(label, key, thumbnails, source)
|
||||
}
|
||||
|
||||
/// An equation rasterised for a tile of `w`×`h` points, as an ink mask.
|
||||
|
||||
@@ -53,23 +53,3 @@ fn font_sample_shows_small_caps_and_the_script_mark() {
|
||||
assert_ne!(draw(&plain, None, false), draw(&plain, sup, false), "the mark is drawn");
|
||||
assert_ne!(draw(&plain, None, false), draw(&plain, None, true), "Switch Modes transforms the preview");
|
||||
}
|
||||
|
||||
/// #7975: a symbol in the Equation tab's strip reads in its tile, not as a speck. The real tile is 24 x 52 pt and the
|
||||
/// picture is fitted into it, so the ink as shown spans a third of the tile's width; wide arrows and operators keep
|
||||
/// their whole ink inside the picture (no clipping).
|
||||
#[test]
|
||||
fn symbol_thumbnails_read_in_the_strips_real_tiles() {
|
||||
let tile = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(24.0, 52.0));
|
||||
for c in ['=', '+', '\u{221E}', '\u{00B1}', '\u{27F9}', '\u{27FA}', '\u{27F7}', '\u{2230}'] {
|
||||
let source = crate::equation_tab::symbol_source(c, Color32::WHITE);
|
||||
let size = source.size_for(&cell_request(tile, 1.0));
|
||||
let img = source.image(size.x, size.y, 1.0).expect("renders");
|
||||
let [w, h] = img.size;
|
||||
let inked: Vec<(usize, usize)> = (0..w * h).filter(|i| img.pixels[*i].a() > 64).map(|i| (i % w, i / w)).collect();
|
||||
let (lo, hi) = (inked.iter().map(|p| p.0).min().unwrap_or(0), inked.iter().map(|p| p.0).max().unwrap_or(0));
|
||||
let fit = (tile.width() / w as f32).min(tile.height() / h as f32);
|
||||
let shown = (hi - lo + 1) as f32 * fit;
|
||||
assert!(shown * 3.0 >= tile.width(), "{c} is a speck: {shown} pt wide in a {} pt tile", tile.width());
|
||||
assert!(lo > 0 && hi + 1 < w, "{c} touches the picture's edge ({lo}..{hi} of {w})");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::menu::ribbon::{Gallery, GalleryFace, GalleryItem, RibbonGroup, RibbonRow};
|
||||
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
|
||||
use craft::ui::buttons::{Arrangement, Button, ToggleButton};
|
||||
use craft::ui::contract::{Gap, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::menu::MenuItem;
|
||||
use craft::ui::primitives::{ContentPainterCx, FacePaint};
|
||||
use craft::ui::primitives::FacePaint;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile};
|
||||
|
||||
use super::common::{menu_button, size_field};
|
||||
use super::{WordApp, json};
|
||||
use crate::equation_tab::pick_tile;
|
||||
|
||||
/// Chart Design and SmartArt Design › Size: the selected graphic's height and width in points. A
|
||||
/// size outside the range is shown as it is and writes nothing.
|
||||
@@ -59,24 +61,14 @@ pub(super) fn smart_art_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
let on = layouts.iter().position(|l| *l == g.layout);
|
||||
let colors = g.colors;
|
||||
let theme = &theme;
|
||||
let line = craft::ui::style::rgba_color(craft::ui::runtime::env::Env::of(ui).tokens.color.text.muted);
|
||||
// One strip of small previews, as the old ribbon: the strip steps and its More button lists them all.
|
||||
let painters: Vec<Box<dyn Fn(&ContentPainterCx, egui::Rect) + '_>> = layouts
|
||||
.iter()
|
||||
.map(|&layout| {
|
||||
Box::new(move |cx: &ContentPainterCx, r: egui::Rect| crate::dialogs_smart_art::preview(cx, r, layout, colors, theme, line))
|
||||
as Box<dyn Fn(&ContentPainterCx, egui::Rect) + '_>
|
||||
})
|
||||
.collect();
|
||||
let items: Vec<GalleryItem<'_, usize>> = layouts
|
||||
.iter()
|
||||
.zip(&painters)
|
||||
.enumerate()
|
||||
.map(|(at, (layout, paint))| GalleryItem { key: at, label: tl!(layout.label()).into(), face: GalleryFace::Paint(&**paint) })
|
||||
.collect();
|
||||
let out = Gallery::new(tl!("Layouts").to_string(), &items, on.as_ref()).tiles(6, 3).aspect(ThumbAspect::new(46, 31)).show(ui);
|
||||
let line = ui.visuals().weak_text_color();
|
||||
let picked = pick_tile(ui, tl!("Layouts"), 4, CaptionPlace::None, on, layouts.len(), |at| match layouts.get(at).copied() {
|
||||
Some(layout) => Tile::new(tl!(layout.label()).to_string())
|
||||
.thumb(ThumbAspect::new(46, 31), move |cx, r| crate::dialogs_smart_art::preview(cx, r, layout, colors, theme, line)),
|
||||
None => Tile::new(String::new()),
|
||||
});
|
||||
// A pick of the current layout does nothing.
|
||||
if let Some(layout) = out.picked.and_then(|i| layouts.get(i)).copied().filter(|l| *l != g.layout) {
|
||||
if let Some(layout) = picked.and_then(|i| layouts.get(i)).copied().filter(|l| *l != g.layout) {
|
||||
let _ = app.run("smartArt.layout", json!({"layout": layout.id()}));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,10 +3,9 @@ use std::ops::RangeInclusive;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
|
||||
use craft::ui::buttons::{Arrangement, Button};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, Sizing, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::controls::disclosure::DisclosureGlyph;
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::menu::{Menu, MenuItem, MenuOutput};
|
||||
@@ -90,17 +89,11 @@ pub(super) fn custom_groups(row: &mut RibbonRow<'_>, app: &mut WordApp, groups:
|
||||
/// Esc cancels. A value outside `range` (points) is shown and writes nothing. `lock_aspect` false
|
||||
/// resizes the one side only.
|
||||
pub(super) fn size_field(ui: &mut Ui, app: &mut WordApp, label: &str, key: &str, pt: f32, lock_aspect: bool, range: RangeInclusive<f32>) {
|
||||
let lengths = crate::options::lengths(app.session.units());
|
||||
let mut events = None;
|
||||
// The label shows beside the field, as the old ribbon drew `H: 252 pt`; the Field makes it the control's one accessible name.
|
||||
Field::new(tl!(label).to_string()).id_salt(("size_field_label", key)).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let field = NumberField::length(tl!(label).to_string(), Bind::given(Some(f64::from(pt))), lengths)
|
||||
.range(f64::from(*range.start())..=f64::from(*range.end()))
|
||||
.id_salt(("size_field", key));
|
||||
events = Some(field.show(ui).edit.events);
|
||||
});
|
||||
let field = NumberField::length(tl!(label).to_string(), Bind::given(Some(f64::from(pt))), crate::options::lengths(app.session.units()))
|
||||
.range(f64::from(*range.start())..=f64::from(*range.end()))
|
||||
.id_salt(("size_field", key));
|
||||
let events = field.show(ui).edit.events;
|
||||
let key = key.to_string();
|
||||
let Some(events) = events else { return };
|
||||
apply_edits(app, events, move |app, v: Option<f64>| {
|
||||
let Some(v) = v.map(|v| v as f32).filter(|v| range.contains(v)) else { return };
|
||||
let params = if lock_aspect { json!({ key.as_str(): v }) } else { json!({ key.as_str(): v, "lockAspect": false }) };
|
||||
|
||||
@@ -392,22 +392,6 @@ fn contextual_tabs_follow_the_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #7974: SmartArt Design keeps its Layouts gallery to one strip, as tall as the other groups, and the Size
|
||||
/// fields show their H: and W: labels.
|
||||
#[test]
|
||||
fn smart_art_design_layouts_are_one_strip_and_size_is_labelled() {
|
||||
use egui::accesskit::Role;
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
a.run("insert.smartArt", json!({"layout": "cycle"})).unwrap();
|
||||
let h = tab_harness(a, "SmartArt Design");
|
||||
let height = |name: &str| h.get_by_role_and_label(Role::Group, name).rect().height();
|
||||
assert!(height("Layouts") <= height("Create Graphic") * 1.2, "Layouts: {} vs {}", height("Layouts"), height("Create Graphic"));
|
||||
for side in ["H:", "W:"] {
|
||||
let roles: Vec<Role> = h.query_all(By::new().label(side)).map(|n| n.accesskit_node().role()).collect();
|
||||
assert_eq!(roles, [Role::SpinButton], "{side} names its field once");
|
||||
}
|
||||
}
|
||||
|
||||
/// No group's content runs into its label: View › Show stacked four check boxes in a column
|
||||
/// made for three, so "Hide White Space" was drawn under "Show". Every tab, every language: each
|
||||
/// control lies inside its group's access node.
|
||||
|
||||
@@ -476,6 +476,9 @@ impl Tokens {
|
||||
on_close: Color32::WHITE,
|
||||
}
|
||||
}
|
||||
pub fn get(ctx: &egui::Context) -> Tokens {
|
||||
if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `faces` after every other font of the interface families.
|
||||
|
||||
@@ -33,12 +33,11 @@ OUTPUT="$DIST/wordcraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/WordCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/WordCraft"
|
||||
cp "$ROOT/assets/app-icon/wordcraft-nightly.icns" "$APP/Contents/Resources/wordcraft-nightly.icns"
|
||||
# Launcher admits notices under Resources/docs, not beside the icon.
|
||||
nightly_copy_notices "$APP/Contents/Resources/docs"
|
||||
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 \
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/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. The unsigned producer also runs with a stub GUI build. These
|
||||
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
|
||||
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
|
||||
@@ -27,8 +27,6 @@ COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"wordcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "WordCraft Nightly.app"
|
||||
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
|
||||
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
@@ -185,50 +183,6 @@ class Fixture:
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def package(self, font_licences):
|
||||
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
|
||||
source = HERE.parents[1]
|
||||
checkout = self.root / "source"
|
||||
checkout.mkdir()
|
||||
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
|
||||
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
|
||||
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
|
||||
"assets/app-icon/wordcraft-nightly.icns"):
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source / relative, target)
|
||||
env = self.env(**dict.fromkeys(SECRETS))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
|
||||
|
||||
git("init", "-q")
|
||||
git("add", "--", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "Packaging fixture")
|
||||
commit = git("rev-parse", "HEAD").strip()
|
||||
version = VERSION[:-12] + commit[:12]
|
||||
# Generated licence text exercises the copier without depending on a font checkout.
|
||||
fonts = self.root / "craft-fonts"
|
||||
for family, data in font_licences.items():
|
||||
licence = fonts / "fonts" / family / "OFL.txt"
|
||||
licence.parent.mkdir(parents=True)
|
||||
licence.write_bytes(data)
|
||||
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
|
||||
(self.bin / "cargo").write_text(
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/wordcraft"\n'
|
||||
'mkdir -p "$(dirname "$gui")"\n'
|
||||
"printf \"#!/bin/sh\\necho 'WordCraft %s (nightly-v1)'\\n\" \"$WORDCRAFT_VERSION\" >\"$gui\"\n",
|
||||
)
|
||||
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
|
||||
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
|
||||
WORDCRAFT_BUILD_CHANNEL="nightly-v1", WORDCRAFT_VERSION=version,
|
||||
WORDCRAFT_BUILD_SHA=commit, WORDCRAFT_BUILD_DATE="2026-11-23")
|
||||
assert result.returncode == 0, result.stdout
|
||||
return self.dist / ASSET.replace(VERSION, version)
|
||||
|
||||
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}
|
||||
@@ -456,40 +410,6 @@ class Verify(unittest.TestCase):
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
|
||||
f = Fixture(self)
|
||||
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
|
||||
archive = f.package(fonts)
|
||||
source = HERE.parents[1]
|
||||
resources = f"{APP}/Contents/Resources"
|
||||
icon = "wordcraft-nightly.icns"
|
||||
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
|
||||
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
|
||||
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
|
||||
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
|
||||
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
|
||||
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
|
||||
contents = f"{APP}/Contents"
|
||||
gui = f"{contents}/MacOS/WordCraft"
|
||||
with zipfile.ZipFile(archive) as zipped:
|
||||
entries = zipped.infolist()
|
||||
names = {entry.filename for entry in entries}
|
||||
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
|
||||
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
|
||||
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
|
||||
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
|
||||
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
|
||||
for path, data in expected_files.items():
|
||||
with self.subTest(path=path):
|
||||
self.assertEqual(zipped.read(path), data)
|
||||
mode = zipped.getinfo(path).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode))
|
||||
self.assertFalse(mode & 0o111)
|
||||
mode = zipped.getinfo(gui).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
|
||||
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
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"):
|
||||
|
||||
@@ -38,49 +38,6 @@ def assert_nightly_serialization(source):
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def caller_entries(lines, indent):
|
||||
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
|
||||
entries = {}
|
||||
children = None
|
||||
for line in lines:
|
||||
if children is not None and line.startswith(" " * (indent + 1)):
|
||||
children.append(line)
|
||||
continue
|
||||
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
|
||||
if row is None or row[1] in entries:
|
||||
raise ValueError("malformed or duplicate caller mapping entry")
|
||||
children = []
|
||||
entries[row[1]] = row[2], children
|
||||
return entries
|
||||
|
||||
|
||||
def assert_caller_secrets(source, job_name, names):
|
||||
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
|
||||
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
||||
root = caller_entries(lines, 0)
|
||||
job_marker, job_lines = root.pop("jobs", (None, []))
|
||||
jobs = caller_entries(job_lines, 2)
|
||||
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
|
||||
raise ValueError("the caller must have one plain job block")
|
||||
job = caller_entries(jobs[job_name][1], 4)
|
||||
if "environment" in job or "environment" in root or "secrets" in root:
|
||||
raise ValueError("only the native callee may bind the environment")
|
||||
if names:
|
||||
if "secrets" not in job:
|
||||
raise ValueError("signer requires an explicit target-specific secret map")
|
||||
mode, secret_lines = job.pop("secrets")
|
||||
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
|
||||
if mode is not None or caller_entries(secret_lines, 6) != expected:
|
||||
raise ValueError("signer must forward exactly the reviewed same-name secret references")
|
||||
elif "secrets" in job:
|
||||
raise ValueError("unsigned caller must not pass secrets")
|
||||
for value, children in (*root.values(), *job.values()):
|
||||
outside_map = "\n".join([value or "", *children])
|
||||
# Scan all remaining text: quoted braces can appear before a secret reference.
|
||||
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
|
||||
raise ValueError("secret bindings belong only in the signer map")
|
||||
|
||||
|
||||
def literal_off(condition):
|
||||
expression = " ".join(condition.split())
|
||||
if expression.startswith("${{") and expression.endswith("}}"):
|
||||
@@ -130,12 +87,6 @@ def job_conditions(jobs):
|
||||
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# The pinned shared registry enables Windows, Linux and macOS for WordCraft.
|
||||
SIGNER_SECRETS = {
|
||||
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
|
||||
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
|
||||
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
|
||||
}
|
||||
# Each platform's one trust field in policy v3, and the public stable identity it must name.
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
@@ -275,49 +226,8 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
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:#]*:")
|
||||
|
||||
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
header = " secrets:\n"
|
||||
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
|
||||
self.assertIn(linux, signer)
|
||||
mutations = {
|
||||
"missing name": signer.replace(linux, ""),
|
||||
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
|
||||
"duplicate name": signer.replace(linux, linux + linux),
|
||||
"duplicate map": signer + header + linux,
|
||||
"quoted duplicate map": signer + ' "secrets": inherit\n',
|
||||
"inherit": signer.split(header)[0] + " secrets: inherit\n",
|
||||
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
|
||||
"yaml merge": signer + " <<: *other\n",
|
||||
"environment": signer + " environment: release\n",
|
||||
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
|
||||
}
|
||||
for change, source in mutations.items():
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(source, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_unsigned_caller_has_no_secrets(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
assert_caller_secrets(producer, "unsigned", set())
|
||||
for suffix in (" secrets: {}\n", " secrets: inherit\n",
|
||||
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
|
||||
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(producer + suffix, "unsigned", set())
|
||||
|
||||
def test_unsigned_caller_refuses_secret_after_format_brace(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
# This inert fixture is never dispatched; the brace is part of the format string.
|
||||
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
|
||||
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
|
||||
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
|
||||
assert_caller_secrets(source, "unsigned", set())
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
|
||||
class NightlyTrustAnchors(unittest.TestCase):
|
||||
|
||||
Reference in New Issue
Block a user