1
//! Layout crate for the Azul GUI framework.
2
//!
3
//! Provides the layout solver (`solver3`), text shaping (`text3`), font
4
//! management (`font`), hit testing, page fragmentation, and widget support.
5
//! Integrates with `azul-core` for DOM types and `azul-css` for style
6
//! properties.
7

            
8
#![doc(
9
    html_logo_url = "https://raw.githubusercontent.com/maps4print/azul/master/assets/images/azul_logo_full_min.svg.png",
10
    html_favicon_url = "https://raw.githubusercontent.com/maps4print/azul/master/assets/images/favicon.ico"
11
)]
12
// Lint policy: deny correctness/safety issues, warn on style (`clippy::all`).
13
//
14
// Crate-wide allows are intentionally limited to lints that are either
15
//   (a) pervasive AND feature-sensitive — an import/binding/field that is unused
16
//       under one feature set is live under another, so a per-site fix would
17
//       break a different feature build — or
18
//   (b) churny / newer-toolchain lints with little value in scoping.
19
// Lints that fire in only a few, well-localized places are scoped with
20
// `#[allow(...)]` on the specific `pub mod` declarations further down, so the
21
// rest of the (hand-written) crate is actually checked.
22
#![deny(unused_must_use)]
23
#![warn(clippy::all)]
24
// Extreme-lint lockdown: all clippy groups plus opt-in rustc lints, enforced as
25
// -D warnings on library code by the CI clippy job. Test builds are exempt via
26
// cfg(not(test)) below since the set is high-noise and low-value on unit and
27
// generated tests; clippy::all correctness still applies to test code.
28
#![cfg_attr(not(test), warn(
29
    clippy::pedantic,
30
    clippy::nursery,
31
    clippy::cargo,
32
    // missing_docs,  // TODO(docs): re-enable as a dedicated final docs pass; disabled
33
    //                // for now so the cleanup focuses on code-quality lints, not doc debt.
34
    missing_debug_implementations,
35
    missing_copy_implementations,
36
    unreachable_pub,
37
    unused_qualifications,
38
    unused_lifetimes,
39
    unused_import_braces,
40
    unused_macro_rules,
41
    unused_crate_dependencies,
42
    meta_variable_misuse,
43
    trivial_casts,
44
    trivial_numeric_casts,
45
    elided_lifetimes_in_paths,
46
    single_use_lifetimes,
47
    variant_size_differences,
48
    non_ascii_idents,
49
    unsafe_op_in_unsafe_fn,
50
    let_underscore_drop,
51
))]
52
#![allow(
53
    // `unknown_lints` lets the two forward-compat lints below be listed even on
54
    // the CI toolchain (1.90), where they may not be known yet, without emitting an
55
    // "unknown lint" warning of their own. They still apply on newer rustc.
56
    unknown_lints,
57
    mismatched_lifetime_syntaxes,          // newer rustc; fires in macro-generated code
58
    function_casts_as_integer,             // newer rustc; widget callback pointer identity
59
    // pervasive + feature-sensitive (unused under one feature, live under another):
60
    unused_imports,
61
    unused_variables,
62
    unused_mut,
63
    dead_code,
64
    // design lint, pervasive across the layout solver / renderer:
65
    clippy::too_many_arguments,
66
    // churny / 3rd-party, low value to scope:
67
    clippy::legacy_numeric_constants,
68
    unexpected_cfgs,                        // web-lift diagnostic cfgs
69
    deprecated,                             // image crate tiff encoder (only under `tiff`)
70
    // transitive dependency-version dups not resolvable in azul's source —
71
    // syn 1↔2 (proc-macro migration), heck/jni-sys/rustc-hash/rustls-webpki;
72
    // re-audit when the dep tree aligns.
73
    clippy::multiple_crate_versions,
74

            
75
    // ── Numeric conversion. A layout + raster engine crosses
76
    // px ↔ device-int ↔ float on essentially every path: a glyph's subpixel
77
    // origin becomes an integer scanline, a u32 pixel index becomes an i32
78
    // span bound, a node count becomes an f32 extent. ~150 sites, none of
79
    // them a defect; scoping each one buries the signal it is supposed to
80
    // carry. Overflow-checked builds (the dev-profile CI job) are what
81
    // actually catch a bad conversion here, and they do — that is how the
82
    // pass-2b tile-blit wrap was found.
83
    clippy::cast_possible_truncation,
84
    clippy::cast_possible_wrap,
85
    clippy::cast_precision_loss,
86
    clippy::cast_sign_loss,
87
    // Exact float comparison is the POINT in the cache/diff paths: "is this
88
    // the same value last frame computed" is a bit-identity question, and an
89
    // epsilon there would make the incremental path silently disagree with a
90
    // fresh render — the one property the equivalence laws pin.
91
    clippy::float_cmp,
92
    // `mul_add` is FUSED, so it changes f32 results. Layout output must stay
93
    // bit-reproducible across builds and platforms (the e2e corpus pins exact
94
    // frames), so the plain `a + b * c` form is deliberate.
95
    clippy::suboptimal_flops,
96
    // Geometry code is x0/x1/y0/y1, w/h, sx/sy, tx/ty — the similarity IS the
97
    // convention, and renaming to satisfy the lint would make it less readable.
98
    clippy::similar_names,
99
    // The solver, the rasterizer and the shaping walkers are long and branchy
100
    // by design: one pass, one place to read it. Splitting them threads state
101
    // through new signatures without making anything clearer.
102
    clippy::too_many_lines,
103
    clippy::cognitive_complexity,
104
    // `Default::default()` inside a struct literal whose field types are
105
    // obvious from the literal itself. Naming the type adds an import and a
106
    // line of noise per site.
107
    clippy::default_trait_access,
108
    // Four break-token builders filter a child list into a Vec and then
109
    // `extend` from it. Inlining the twelve-line borrow-capturing iterator
110
    // into each `extend` call saves one small allocation on a COLD page-break
111
    // path, in the code whose correctness the pagination suite exists to
112
    // protect. Not a trade worth making; revisit if a profile disagrees.
113
    clippy::needless_collect,
114
    // Nursery lint that wants `map_or_else` for every if-let/match. On the
115
    // multi-arm dispatch chains in this crate the rewrite nests closures
116
    // inside each other's else-branch; see the same call in azul-core.
117
    clippy::option_if_let_else,
118
    // A helper item declared next to the statements that use it, rather than
119
    // hoisted to the top of the function, is a deliberate locality choice.
120
    clippy::items_after_statements,
121
    // Arms that happen to share a body are frequently distinct CASES that
122
    // must stay separately readable (and separately editable) — merging them
123
    // by body is a refactor hazard, not a cleanup.
124
    clippy::match_same_arms,
125
    // By-value parameters are the C-ABI shape: generated bindings hand
126
    // ownership across the boundary.
127
    clippy::needless_pass_by_value,
128
    // Would force a `S: BuildHasher` parameter onto public API for no gain.
129
    clippy::implicit_hasher,
130
    // Types carrying f32 geometry cannot implement `Eq`.
131
    clippy::derive_partial_eq_without_eq,
132

            
133
    // ── Documentation prose. Deferred to the same dedicated docs pass as
134
    // `missing_docs` above (see the TODO there): these are shape-of-the-prose
135
    // lints over existing, accurate doc comments, not missing or wrong docs.
136
    clippy::too_long_first_doc_paragraph,
137
    clippy::doc_lazy_continuation,
138
    clippy::missing_panics_doc,
139
    clippy::missing_errors_doc,
140
)]
141

            
142
#[macro_use]
143
extern crate alloc;
144
extern crate core;
145
// Let this crate refer to itself as `azul_layout::…`. The e2e/debug-server port
146
// (`src/e2e/full.rs`) was written verbatim against the published crate name; the
147
// self-alias makes those ~80 `azul_layout::…` paths resolve without editing them.
148
extern crate self as azul_layout;
149

            
150
// Dependencies kept for downstream/feature-plumbing use but not referenced
151
// directly in this crate's source — marked intentionally linked so
152
// unused_crate_dependencies stays quiet (the lint's own suggested fix).
153
// `brotli-decompressor`: decompresses the codegen material_icons.ttf.br in azul-dll.
154
#[cfg(feature = "icons")]
155
use brotli_decompressor as _;
156
// `lru`: reserved for the slippy-map tile cache (azul-dll widgets).
157
use lru as _;
158
// `rustls` / `webpki-roots`: selected through ureq's `rustls-no-provider` +
159
// `rustls-webpki-roots` features and reached only via `ureq::tls::*`, so this
160
// crate never names them — but it must depend on them to pin the versions
161
// ureq resolves against (see the `http` feature).
162
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
163
use rustls as _;
164
// `unicode-normalization` / `xmlwriter`: pulled by text_layout / xml for the
165
// shaping + SVG-writer paths consumed downstream.
166
#[cfg(feature = "text_layout")]
167
use unicode_normalization as _;
168
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
169
use webpki_roots as _;
170
#[cfg(feature = "xml")]
171
use xmlwriter as _;
172
// `libc`: the probe feature's rusage/dladdr calls exist on unix only.
173
#[cfg(all(feature = "probe", not(unix)))]
174
use libc as _;
175

            
176
/// Web-lift diagnostic marker: a volatile store of `val` to the absolute wasm
177
/// linear-memory address `addr` (the 0x40000–0xF0000 free band the e2e harness
178
/// peeks via `AzStartup_peekU32`).
179
///
180
/// Compiles to NOTHING without the `web_lift`
181
/// feature — absolute-address stores would segfault native builds (macOS
182
/// `__PAGEZERO` covers the low 4 GiB). All in-tree diagnostic markers MUST go
183
/// through this helper rather than calling `core::ptr::write_volatile` on a
184
/// literal address directly.
185
///
186
/// # Safety
187
///
188
/// With the `web_lift` feature enabled, `addr` must be a valid, writable wasm
189
/// linear-memory address (within the 0x40000–0xF0000 diagnostic band). Without
190
/// the feature this is a no-op and always safe.
191
#[cfg(feature = "web_lift")]
192
#[inline]
193
pub unsafe fn az_mark(_addr: u32, _val: u32) {
194
    // Volatile isn't const-callable, so this variant is a plain (non-const) fn.
195
    core::ptr::write_volatile(_addr as usize as *mut u32, _val);
196
}
197
/// No-op `const` variant used when the `web_lift` feature is off.
198
///
199
/// # Safety
200
///
201
/// Always safe — this variant does nothing; the `unsafe` marker only exists to
202
/// keep the signature identical to the `web_lift` variant so call sites compile
203
/// unchanged under both features.
204
#[cfg(not(feature = "web_lift"))]
205
#[inline]
206
3528196
pub const unsafe fn az_mark(_addr: u32, _val: u32) {}
207

            
208
/// Read counterpart of [`az_mark`] (marker counters like `0x60758`).
209
/// Returns 0 without the `web_lift` feature.
210
///
211
/// # Safety
212
///
213
/// With the `web_lift` feature enabled, `addr` must be a valid, readable wasm
214
/// linear-memory address (within the 0x40000–0xF0000 diagnostic band). Without
215
/// the feature this is a no-op that returns 0 and is always safe.
216
#[cfg(feature = "web_lift")]
217
#[inline]
218
#[must_use]
219
pub unsafe fn az_mark_read(_addr: u32) -> u32 {
220
    // Volatile isn't const-callable, so this variant is a plain (non-const) fn.
221
    core::ptr::read_volatile(_addr as usize as *const u32)
222
}
223
/// No-op `const` variant (returns 0) used when the `web_lift` feature is off.
224
///
225
/// # Safety
226
///
227
/// Always safe — returns 0 and touches nothing; the `unsafe` marker only exists
228
/// to keep the signature identical to the `web_lift` variant.
229
#[cfg(not(feature = "web_lift"))]
230
#[inline]
231
#[must_use]
232
367037
pub const unsafe fn az_mark_read(_addr: u32) -> u32 {
233
367037
    0
234
367037
}
235

            
236
/// Process-wide `AppConfig` snapshot (app name/version, update manifest,
237
/// changelog + support-mailbox URLs) published by `App::run`, read by the
238
/// updater and the system dialogs.
239
#[cfg(feature = "std")]
240
pub mod appenv;
241
/// Built-in system dialogs (`SysDialogType`): report-a-problem, update
242
/// checker with Markdown changelog, crash reporter. ALWAYS CPU-rendered.
243
#[cfg(all(feature = "std", feature = "widgets", feature = "text_layout"))]
244
pub mod dialogs;
245
/// Font traits available regardless of text layout feature.
246
pub mod font_traits;
247
/// Image decoding and encoding (wraps the `image` crate).
248
#[cfg(feature = "image_decoding")]
249
pub mod image;
250
/// Pure-functional image resampling (area downscale / bilinear upscale): the
251
/// golden-reference scaler shared by the CPU rasterizer, the capture pipeline
252
/// and any `RawImage` resize. No `image`-crate or platform dependency.
253
pub mod image_scale;
254
/// The ACTION JOURNAL: a bounded breadcrumb trail of dispatched callbacks,
255
/// for problem reports and crash dumps. Off until enabled.
256
#[cfg(feature = "std")]
257
pub mod journal;
258
/// Scroll, hover, clipboard, cursor, and focus managers.
259
#[cfg(feature = "text_layout")]
260
// Scoped (was crate-wide): internal manager types exposed for tests.
261
#[allow(private_interfaces)]
262
pub mod managers;
263
/// Optional probe instrumentation. With the `probe` feature off this
264
/// is a tiny module of no-op stubs and pays zero cost.
265
pub mod probe;
266
pub mod resource_handles;
267
/// CSS layout solver: block, inline, flex, grid, and table formatting.
268
#[cfg(feature = "text_layout")]
269
// Scoped (was crate-wide): solver internals — intentional `drop(&_)` scope
270
// markers, internal types exposed for tests, incremental-relayout assignments,
271
// generated/parenthesized property code, and exhaustive generated matches.
272
#[allow(
273
    dropping_references,
274
    private_interfaces,
275
    unreachable_patterns,
276
    unused_parens,
277
    unused_doc_comments,
278
    unused_assignments
279
)]
280
pub mod solver3;
281
/// Opt-in telemetry client: consent tiers, OTLP/HTTP JSON encoding, a
282
/// disk-backed ping queue and an uploader. Requires the `telemetry`
283
/// feature (std-only); collection stays *off* at runtime until a consent
284
/// tier is configured, so linking it in does not by itself send anything.
285
#[cfg(feature = "telemetry")]
286
// Scoped allows, per the crate lint policy above:
287
//   * the submodule names (`config`, `metrics`) are the public API grouping, while the types are
288
//     re-exported at `telemetry::*` where the `Telemetry` prefix is what disambiguates them from
289
//     every other `Config` in the tree;
290
//   * the registry and the config cell are global-by-design, so their guards are held across the
291
//     whole read/modify they protect — tightening the drop would split an atomic update in half;
292
//   * `missing_const_for_fn` fires on accessors that read a `static` today and will read more
293
//     tomorrow; making them `const` is not a promise this API wants to keep.
294
#[allow(
295
    clippy::module_name_repetitions,
296
    clippy::significant_drop_tightening,
297
    clippy::missing_const_for_fn
298
)]
299
pub mod telemetry;
300
/// Version checking + update policy (Phase 4): manifest source, install-kind
301
/// backstops (package-managed binaries never self-update), anti-downgrade,
302
/// cooldown/suspend state. Requires the `updater` feature.
303
#[cfg(feature = "updater")]
304
pub mod updater;
305

            
306
/// C-compatible string formatting via `strfmt`.
307
#[cfg(feature = "strfmt")]
308
pub mod fmt;
309
#[cfg(feature = "strfmt")]
310
pub use fmt::{fmt_string, FmtArg, FmtArgVec, FmtArgVecDestructor, FmtValue};
311

            
312
/// Built-in widgets: button, text input, tabs, tree view, node graph, etc.
313
#[cfg(feature = "widgets")]
314
// Scoped (was crate-wide): incremental widget-state assignments and the
315
// node_graph extern "C" fn that returns `()`.
316
#[allow(unused_assignments, improper_ctypes_definitions)]
317
pub mod widgets;
318

            
319
/// Desktop platform helpers (file dialogs, notifications).
320
#[cfg(feature = "extra")]
321
pub mod desktop;
322

            
323
/// ICU internationalization: date/time formatting, plurals, list formatting.
324
#[cfg(any(
325
    feature = "icu",
326
    all(target_os = "macos", feature = "icu_macos"),
327
    all(target_os = "windows", feature = "icu_windows"),
328
))]
329
pub mod icu;
330
#[cfg(any(
331
    feature = "icu",
332
    all(target_os = "macos", feature = "icu_macos"),
333
    all(target_os = "windows", feature = "icu_windows"),
334
))]
335
pub use icu::{
336
    DateTimeFieldSet, FormatLength, IcuDate, IcuDateTime, IcuError, IcuLocalizer,
337
    IcuLocalizerHandle, IcuResult, IcuStringVec, IcuTime, LayoutCallbackInfoIcuExt, ListType,
338
    PluralCategory,
339
};
340

            
341
/// Project Fluent localization: message bundles, argument formatting, ZIP I/O.
342
#[cfg(feature = "fluent")]
343
pub mod fluent;
344
/// URL parsing (RFC 3986 compliant). Pure-Rust, always present (no TLS deps).
345
/// URL types live in `azul_core::url`; re-exported so `azul_layout::url::*`
346
/// keeps resolving. `Url::parse`/`join` are enabled via the `http` feature
347
/// (which turns on `azul-core/url`).
348
pub use azul_core::url;
349
pub use azul_core::url::{ResultUrlUrlParseError, Url, UrlParseError};
350
#[cfg(feature = "fluent")]
351
pub use fluent::{
352
    check_fluent_syntax, check_fluent_syntax_bytes, create_fluent_zip,
353
    create_fluent_zip_from_strings, export_to_zip, FluentError, FluentLanguageInfo,
354
    FluentLanguageInfoVec, FluentLoadError, FluentLoadErrorVec, FluentLocalizerHandle,
355
    FluentSyntaxCheckResult, FluentZipLoadResult,
356
};
357

            
358
/// File system operations (C-compatible wrappers for `std::fs`).
359
// Scoped (was crate-wide): `///` doc comments before `impl_vec!`/`impl_option!`
360
// macro invocations, and an infallible inherent `FilePath::from_str` (returns
361
// `Self`, so it cannot implement the fallible `FromStr` trait).
362
#[allow(unused_doc_comments, clippy::should_implement_trait)]
363
pub mod file;
364
pub use file::{
365
    dir_create, dir_create_all, dir_delete, dir_delete_all, dir_list, file_append, file_copy,
366
    file_delete, file_metadata, file_read, file_read_string, file_rename, file_write,
367
    file_write_string, path_canonicalize, path_exists, path_extension, path_file_name, path_is_dir,
368
    path_is_file, path_join, path_parent, temp_dir, DirEntry, DirEntryVec, DirEntryVecDestructor,
369
    DirEntryVecDestructorType, FileError, FileErrorKind, FileMetadata, FilePath, OptionFilePath,
370
};
371

            
372
/// HTTP client: GET/POST requests with pure-Rust TLS.
373
///
374
/// API surface always present (stub when off); ureq/rustls only pulled in with `http`.
375
/// One way to turn a URI into bytes, whatever scheme it names - `file://`,
376
/// a bare path, or `http(s)://` through [`http`].
377
pub mod fetch;
378
pub mod http;
379
pub use http::{
380
    download_bytes, download_bytes_with_config, http_get, http_get_with_config, http_post,
381
    http_post_with_config, http_put_with_config, http_request_with_config, is_url_reachable,
382
    HttpError, HttpHeader, HttpMethod, HttpRequestConfig, HttpResponse, HttpResponseTooLargeError,
383
    HttpResult, HttpStatusError,
384
};
385

            
386
/// JSON parsing and serialization for the C API.
387
#[cfg(feature = "json")]
388
pub mod json;
389
#[cfg(feature = "json")]
390
pub use json::{
391
    json_parse, json_stringify, Json, JsonInternal, JsonKeyValue, JsonKeyValueVec,
392
    JsonKeyValueVecDestructor, JsonKeyValueVecDestructorType, JsonParseError, JsonType, JsonVec,
393
    OptionJson, OptionJsonKeyValueVec, OptionJsonVec, ResultJsonJsonParseError,
394
};
395

            
396
/// UUID string generation (`Uuid::v4` / `Uuid::short`) - the mint for
397
/// collision-free MARKER strings (`Dom::with_marker`).
398
pub mod uuid;
399

            
400
/// ZIP file creation, extraction, and listing.
401
#[cfg(feature = "zip")]
402
pub mod zip;
403
#[cfg(feature = "zip")]
404
pub use zip::{
405
    zip_create, zip_create_from_files, zip_extract_all, zip_list_contents, ZipFile, ZipFileEntry,
406
    ZipFileEntryVec, ZipPathEntry, ZipPathEntryVec, ZipReadConfig, ZipReadError, ZipWriteConfig,
407
    ZipWriteError,
408
};
409

            
410
/// Icon provider: resolves icons from Material Icons font, images, or ZIP packs.
411
pub mod icon;
412
// Re-export core icon types
413
pub use azul_core::icon::{
414
    resolve_icons_in_dom, styled_dom_resolving_icons, IconProviderHandle, IconResolverCallbackType,
415
    IconViewState, OptionIconProviderHandle,
416
};
417
pub use icon::{
418
    create_default_icon_provider,
419
    // Resolver
420
    default_icon_resolver,
421
    register_embedded_material_icons,
422
    register_font_icon,
423
    register_icons_from_zip,
424
    // Helpers
425
    register_image_icon,
426
    register_material_icons,
427
    FontIconData,
428
    // Data types for RefAny
429
    ImageIconData,
430
};
431

            
432
/// Callback handling for layout events (invocation, result processing).
433
#[cfg(feature = "text_layout")]
434
pub mod callbacks;
435
/// CPU-based software rendering (no GPU required).
436
#[cfg(feature = "cpurender")]
437
// Scoped (was crate-wide): complex rasterizer signatures.
438
#[allow(clippy::type_complexity)]
439
pub mod cpurender;
440
/// Default keyboard actions (copy, paste, select-all, undo, etc.).
441
#[cfg(feature = "text_layout")]
442
pub mod default_actions;
443
/// Apply structural `DocumentOperation`s to a plain XML tree.
444
///
445
/// The Path-2 helper for apps without their own document model (the PDF
446
/// editor).
447
#[cfg(all(feature = "text_layout", feature = "xml"))]
448
pub mod document_edit;
449
/// Post-layout developer warnings for raw text nodes used without a
450
/// containing block (azul does not auto-wrap them the way browsers do).
451
///
452
/// Reads computed display through `solver3::getters`, so it exists only
453
/// where the layout solver does — same gate as `window` and
454
/// `default_actions`, its only caller being inside `window`.
455
#[cfg(feature = "text_layout")]
456
pub mod dom_lint;
457
/// Event determination: maps raw input to DOM node callbacks.
458
#[cfg(feature = "text_layout")]
459
pub mod event_determination;
460
/// Font parsing, metrics extraction, and subsetting.
461
#[cfg(feature = "text_layout")]
462
// Scoped (was crate-wide): complex font-table signatures.
463
#[allow(clippy::type_complexity)]
464
pub mod font;
465
/// HTML form constraint validation (`required`, `minlength`, `pattern`, ...).
466
///
467
/// Needs `text_layout` for `crate::window::DomLayoutResult` and `std` because
468
/// `regex-lite` declares `compile_error!` without its own `std` feature.
469
#[cfg(all(feature = "text_layout", feature = "std"))]
470
pub mod form;
471
/// Glyph path and cell cache for CPU text rendering.
472
#[cfg(feature = "cpurender")]
473
pub mod glyph_cache;
474
/// The request / resume primitive: where resumable API functions park their
475
/// callbacks until the runtime delivers the result as a fresh activation.
476
#[cfg(feature = "text_layout")]
477
pub mod request;
478

            
479
/// Headless backend for CPU-only rendering without a display server.
480
///
481
/// Used with `AZUL_HEADLESS=1` for E2E testing, CI, and screenshot capture.
482
#[cfg(feature = "text_layout")]
483
pub mod headless;
484
// Re-export allsorts types needed by printpdf
485
#[cfg(feature = "text_layout")]
486
pub use allsorts::subset::CmapTarget;
487
#[cfg(feature = "text_layout")]
488
pub use font::parsed::{
489
    FontParseWarning, FontParseWarningSeverity, FontType, OwnedGlyph, ParsedFont, PdfFontMetrics,
490
    SubsetFont,
491
};
492
// Re-export hyphenation for external crates (like printpdf)
493
#[cfg(feature = "text_layout_hyphenation")]
494
pub use hyphenation;
495
/// Hit-testing: maps screen coordinates to DOM nodes.
496
#[cfg(feature = "text_layout")]
497
pub mod hit_test;
498
/// Paged media: the `FragmentationContext` (continuous vs. paged) and page margins.
499
/// The primitive types live in `azul_core::paged`; re-exported here so existing
500
/// `azul_layout::paged::*` / `crate::paged::*` paths keep resolving.
501
pub use azul_core::paged;
502
/// Content overlay + journal for quickly-mutable content.
503
///
504
/// The single write chokepoint and overlay→DOM read order (images now,
505
/// text/structural next).
506
#[cfg(feature = "text_layout")]
507
pub mod overlay;
508
/// Scroll physics timer for momentum-based smooth scrolling.
509
#[cfg(feature = "text_layout")]
510
pub mod scroll_timer;
511
/// Text shaping, line breaking (Knuth-Plass), and inline formatting.
512
#[cfg(feature = "text_layout")]
513
// Scoped (was crate-wide): internal types exposed for tests, a labelled
514
// shaping loop, and complex shaping/cache signatures.
515
#[allow(private_interfaces, unused_labels, clippy::type_complexity)]
516
pub mod text3;
517
/// Thread callback wrappers for the C API.
518
#[cfg(feature = "text_layout")]
519
pub mod thread;
520
/// Timer callback wrappers for the C API.
521
#[cfg(feature = "text_layout")]
522
// Scoped (was crate-wide): hand-written `Ord`/`PartialOrd` on a timer type.
523
#[allow(clippy::non_canonical_partial_ord_impl)]
524
pub mod timer;
525
pub mod transient;
526
/// Render an icon-registry entry to RGBA pixels, for the system tray.
527
/// Goes through the same `<icon>` resolution + CPU renderer, so every icon
528
/// kind (and any future DOM-expressible one) works without a special case --
529
/// which is why it needs `cpurender` too: both of its public items exist to
530
/// rasterize an icon, and `render_icon_to_rgba` calls
531
/// `cpurender::render_component_preview` directly.
532
#[cfg(all(feature = "text_layout", feature = "std", feature = "cpurender"))]
533
pub mod tray_icon;
534
/// Window layout management: relayout, event processing, state sync.
535
#[cfg(feature = "text_layout")]
536
// Scoped (was crate-wide): parenthesized layout expressions.
537
#[allow(unused_parens)]
538
pub mod window;
539
/// Window state types (keyboard, mouse, DPI, focus).
540
#[cfg(feature = "text_layout")]
541
pub mod window_state;
542
/// XML and XHTML parsing for declarative UI definitions.
543
#[cfg(feature = "xml")]
544
// Scoped (was crate-wide): incremental parser-state assignments.
545
#[allow(unused_assignments)]
546
pub mod xml;
547

            
548
/// Debug / E2E server op-dispatch, ported verbatim from the DLL. Gated behind
549
/// the `e2e-server` feature (NOT in `default`), so the lean crate is unaffected.
550
#[cfg(feature = "e2e-server")]
551
pub mod e2e;
552

            
553
// Export the main layout function and window management
554
#[cfg(feature = "text_layout")]
555
pub use hit_test::{CursorTypeHitTest, FullHitTest};
556
#[cfg(feature = "text_layout")]
557
pub use managers::text_input::{OptionPendingTextEdit, PendingTextEdit};
558
/// Canonical paged-media page margins (defined in [`paged`]).
559
pub use paged::PageMargins;
560
#[cfg(feature = "font_async_registry")]
561
pub use rust_fontconfig::registry::FcFontRegistry;
562
#[cfg(feature = "text_layout")]
563
pub use solver3::cache::LayoutCache as Solver3LayoutCache;
564
#[cfg(feature = "text_layout")]
565
pub use solver3::display_list::DisplayList as DisplayList3;
566
#[cfg(feature = "text_layout")]
567
pub use solver3::layout_document;
568
#[cfg(feature = "text_layout")]
569
pub use solver3::paged_layout::layout_document_paged;
570
/// The analysis-returning paged entries + the precalculation-only path
571
/// (document editors: page count / page-of-node WITHOUT materializing pages).
572
#[cfg(feature = "text_layout")]
573
pub use solver3::paged_layout::{
574
    compute_document_pagination, layout_document_paged_v2, pagination_to_dom_breaks,
575
    spine_path_at_y, BreaksDelta, PagedLayoutResult, PaginationSession, StructuralBreak,
576
};
577
/// Standalone page-break analysis (typed breaks, spans, policy, lazy pages).
578
#[cfg(feature = "text_layout")]
579
pub use solver3::{
580
    display_list::paginate_single_page,
581
    page_breaks::{
582
        compute_page_breaks, compute_page_breaks_from_display_list,
583
        compute_page_breaks_with_report, compute_page_breaks_with_sequence, page_of_y, page_spans,
584
        recompute_page_breaks_from, BreakKind, BreakPolicy, MonolithReason, MonolithWarning,
585
        PageBreakInput, PageBreakPosition, PageConstraints, PaginationInfo,
586
    },
587
    pagination::{PageSequence, PageSetup},
588
};
589
#[cfg(feature = "text_layout")]
590
pub use solver3::{LayoutContext, LayoutError, Result as LayoutResult3};
591
/// Backwards-compat alias for the old `TextLayoutCache` name.
592
/// Will be dropped at the next API revision; new code should use
593
/// [`TextShapingCache`] directly.
594
#[cfg(feature = "text_layout")]
595
pub use text3::cache::TextShapingCache as TextLayoutCache;
596
#[cfg(feature = "text_layout")]
597
pub use text3::cache::{FontContext, FontManager, TextShapingCache};
598
#[cfg(feature = "text_layout")]
599
pub use window::{CursorBlinkTimerAction, LayoutWindow, ScrollbarDragState, TooltipTimerAction};
600

            
601
#[cfg(feature = "text_layout")]
602
/// Parses raw font bytes into a [`FontRef`](azul_css::props::basic::FontRef)
603
/// suitable for use in the layout system.
604
// signature must match the `ParseFontFn = fn(LoadedFontSource) -> ...` callback type
605
// (core/src/resources.rs) and the api.json export, so the owned param cannot become &.
606
#[allow(clippy::needless_pass_by_value)]
607
428
pub fn parse_font_fn(
608
428
    source: azul_core::resources::LoadedFontSource,
609
428
) -> Option<azul_css::props::basic::FontRef> {
610
    use crate::font::parsed::ParsedFont;
611

            
612
428
    ParsedFont::from_bytes(
613
428
        source.data.as_ref(),
614
428
        source.index as usize,
615
428
        &mut Vec::new(), // Ignore warnings for now
616
    )
617
428
    .map(parsed_font_to_font_ref)
618
428
}
619

            
620
#[cfg(feature = "text_layout")]
621
/// Wraps a [`ParsedFont`] in a [`FontRef`](azul_css::props::basic::FontRef),
622
/// transferring ownership to the returned handle.
623
23449
pub fn parsed_font_to_font_ref(parsed_font: ParsedFont) -> azul_css::props::basic::FontRef {
624
    use core::ffi::c_void;
625

            
626
23449
    extern "C" fn parsed_font_destructor(ptr: *mut c_void) {
627
23449
        unsafe {
628
23449
            drop(Box::from_raw(ptr.cast::<ParsedFont>()));
629
23449
        }
630
23449
    }
631

            
632
23449
    let boxed = Box::new(parsed_font);
633
23449
    let raw_ptr = Box::into_raw(boxed) as *const c_void;
634
23449
    azul_css::props::basic::FontRef::new(raw_ptr, parsed_font_destructor)
635
23449
}
636

            
637
#[cfg(feature = "text_layout")]
638
/// Recovers a reference to the [`ParsedFont`] stored inside a
639
/// [`FontRef`](azul_css::props::basic::FontRef).
640
///
641
/// # Safety contract
642
/// The `font_ref` must have been created by [`parsed_font_to_font_ref`],
643
/// so that `font_ref.parsed` points to a valid `ParsedFont`.
644
#[must_use]
645
2782033
pub const fn font_ref_to_parsed_font(font_ref: &azul_css::props::basic::FontRef) -> &ParsedFont {
646
    // SAFETY: `font_ref.parsed` was created by `parsed_font_to_font_ref`
647
    // via `Box::into_raw`, so it points to a valid, aligned `ParsedFont`.
648
2782033
    unsafe { &*font_ref.parsed.cast::<ParsedFont>() }
649
2782033
}
650

            
651
#[cfg(test)]
652
mod autotest_generated {
653
    //! Adversarial unit tests generated by the autotest fleet.
654
    //!
655
    //! Covers the four items defined directly in `lib.rs`:
656
    //!   * `az_mark` / `az_mark_read` — the web-lift diagnostic markers. Only the
657
    //!     `#[cfg(not(feature = "web_lift"))]` (no-op `const`) variants are exercised: the
658
    //!     `web_lift` variants store to *absolute* addresses and would segfault a native test
659
    //!     binary, so they are deliberately untested here (the doc comment says as much).
660
    //!   * `parse_font_fn` — raw bytes → `Option<FontRef>`.
661
    //!   * `parsed_font_to_font_ref` / `font_ref_to_parsed_font` — the `Box::into_raw` / reborrow
662
    //!     round-trip, plus the refcounted clone/drop contract of the `FontRef` handle those two
663
    //!     produce.
664

            
665
    use super::*;
666

            
667
    // ---------------------------------------------------------------
668
    // az_mark / az_mark_read  (numeric — no-op variants)
669
    // ---------------------------------------------------------------
670

            
671
    /// Without `web_lift` the read is documented to return 0 for *every* address,
672
    /// including the ends of the u32 range and the 0x40000–0xF0000 diagnostic band.
673
    /// A non-zero answer here would mean the native build is really dereferencing
674
    /// an absolute address.
675
    #[cfg(not(feature = "web_lift"))]
676
    #[test]
677
    fn az_mark_read_is_zero_for_every_boundary_address() {
678
        let addresses = [
679
            0u32,
680
            1,
681
            0x3_FFFF,        // one below the diagnostic band
682
            0x4_0000,        // band start
683
            0x6_0758,        // a real marker counter from the docs
684
            0xF_0000,        // band end
685
            0xF_0001,        // one past the band
686
            i32::MIN as u32, // "negative" input, reinterpreted
687
            (-1i32) as u32,  // == u32::MAX
688
            u32::MAX - 1,
689
            u32::MAX,
690
            u32::MAX.wrapping_add(1), // wraps to 0, must not panic
691
        ];
692
        for addr in addresses {
693
            assert_eq!(unsafe { az_mark_read(addr) }, 0, "az_mark_read(0x{addr:x})");
694
        }
695
    }
696

            
697
    /// Sweep the whole u32 address space at a coarse stride: no address may panic
698
    /// or return anything but 0.
699
    #[cfg(not(feature = "web_lift"))]
700
    #[test]
701
    fn az_mark_read_sweeps_the_whole_address_space_as_zero() {
702
        for addr in (0u32..=u32::MAX).step_by(1 << 24) {
703
            assert_eq!(unsafe { az_mark_read(addr) }, 0);
704
        }
705
    }
706

            
707
    /// A write must remain unobservable (the no-op variant stores nothing), for
708
    /// every combination of boundary address and boundary value.
709
    #[cfg(not(feature = "web_lift"))]
710
    #[test]
711
    fn az_mark_writes_are_unobservable_without_web_lift() {
712
        let addresses = [0u32, 0x4_0000, 0x6_0758, 0xF_0000, u32::MAX];
713
        let values = [
714
            0u32,
715
            1,
716
            u32::MAX / 2,
717
            u32::MAX - 1,
718
            u32::MAX,
719
            i32::MIN as u32,
720
        ];
721
        for addr in addresses {
722
            for val in values {
723
                unsafe { az_mark(addr, val) };
724
                assert_eq!(
725
                    unsafe { az_mark_read(addr) },
726
                    0,
727
                    "az_mark(0x{addr:x}, {val}) must not be observable"
728
                );
729
            }
730
        }
731
        // Repeating a write is still a no-op (idempotent, no accumulating state).
732
        for _ in 0..1_000 {
733
            unsafe { az_mark(0x6_0758, u32::MAX) };
734
        }
735
        assert_eq!(unsafe { az_mark_read(0x6_0758) }, 0);
736
    }
737

            
738
    /// Both no-op variants are `const fn`; this fails to *compile* if that ever
739
    /// regresses (the `web_lift` variants are non-const on purpose, so this test
740
    /// is gated off there).
741
    #[cfg(not(feature = "web_lift"))]
742
    #[test]
743
    fn az_mark_no_op_variants_are_const_evaluable() {
744
        const _WRITE_MIN: () = unsafe { az_mark(0, 0) };
745
        const _WRITE_MAX: () = unsafe { az_mark(u32::MAX, u32::MAX) };
746
        const READ_ZERO: u32 = unsafe { az_mark_read(0) };
747
        const READ_MAX: u32 = unsafe { az_mark_read(u32::MAX) };
748
        assert_eq!(READ_ZERO, 0);
749
        assert_eq!(READ_MAX, 0);
750
    }
751

            
752
    // ---------------------------------------------------------------
753
    // Shared font fixtures (text_layout only)
754
    // ---------------------------------------------------------------
755

            
756
    /// Positive control: the built-in `Azul Mock Mono` font (96 glyphs, upem 1000).
757
    #[cfg(feature = "text_layout")]
758
    const MOCK_MONO: &[u8] = text3::mock_fonts::MOCK_MONO_TTF;
759

            
760
    #[cfg(feature = "text_layout")]
761
    fn loaded_source(bytes: Vec<u8>, index: u32) -> azul_core::resources::LoadedFontSource {
762
        azul_core::resources::LoadedFontSource {
763
            data: azul_css::U8Vec::from_vec(bytes),
764
            index,
765
            load_outlines: true,
766
        }
767
    }
768

            
769
    #[cfg(feature = "text_layout")]
770
    fn parse_mock() -> ParsedFont {
771
        ParsedFont::from_bytes(MOCK_MONO, 0, &mut Vec::new())
772
            .expect("Azul Mock Mono must parse (positive control)")
773
    }
774

            
775
    // ---------------------------------------------------------------
776
    // parse_font_fn  (parser)
777
    // ---------------------------------------------------------------
778

            
779
    /// Malformed / hostile byte soup must come back as `None`, never a panic and
780
    /// never a bogus `FontRef` (which would later be dereferenced as a `ParsedFont`).
781
    #[cfg(feature = "text_layout")]
782
    #[test]
783
    fn parse_font_fn_rejects_malformed_input() {
784
        let cases: Vec<(&str, Vec<u8>)> = vec![
785
            ("empty", Vec::new()),
786
            ("single_nul", vec![0u8]),
787
            ("whitespace_only", b"   \t\n".to_vec()),
788
            ("garbage", (0u8..=255).cycle().take(4096).collect()),
789
            ("invalid_utf8", vec![0xFF, 0xFE, 0x00]),
790
            ("sfnt_magic_only", vec![0x00, 0x01, 0x00, 0x00]),
791
            ("header_only", MOCK_MONO[..12].to_vec()),
792
            ("truncated_font", MOCK_MONO[..64].to_vec()),
793
            ("half_a_font", MOCK_MONO[..MOCK_MONO.len() / 2].to_vec()),
794
            (
795
                "unicode_emoji",
796
                "\u{1F600}\u{1F600}".repeat(1_000).into_bytes(),
797
            ),
798
            ("combining_marks", "e\u{0301}".repeat(10_000).into_bytes()),
799
            ("nested_brackets", vec![b'['; 10_000]),
800
            (
801
                "boundary_numbers",
802
                b"0 -0 9223372036854775807 NaN inf -inf 1e309".to_vec(),
803
            ),
804
            ("leading_junk_then_font", {
805
                let mut v = b"garbage".to_vec();
806
                v.extend_from_slice(MOCK_MONO);
807
                v
808
            }),
809
        ];
810
        for (name, bytes) in cases {
811
            assert!(
812
                parse_font_fn(loaded_source(bytes, 0)).is_none(),
813
                "{name} must not parse into a FontRef"
814
            );
815
        }
816
    }
817

            
818
    /// Multi-megabyte junk: must terminate quickly and return `None`, not hang or
819
    /// allocate its way out of memory (the sfnt table directory is attacker-controlled).
820
    #[cfg(feature = "text_layout")]
821
    #[test]
822
    fn parse_font_fn_survives_extremely_long_input() {
823
        assert!(parse_font_fn(loaded_source(vec![0u8; 1_000_000], 0)).is_none());
824
        assert!(parse_font_fn(loaded_source(vec![b'a'; 1_000_000], 0)).is_none());
825
        // "ttcf" collection magic followed by a megabyte of junk offsets.
826
        let mut ttcf = b"ttcf".to_vec();
827
        ttcf.extend_from_slice(&vec![0xABu8; 1_000_000]);
828
        assert!(parse_font_fn(loaded_source(ttcf, 0)).is_none());
829
    }
830

            
831
    /// Positive control: a real font parses, and the handle we get back really does
832
    /// point at the parsed face (this is the only sanctioned way to build the
833
    /// `FontRef` that `font_ref_to_parsed_font` is allowed to reborrow).
834
    #[cfg(feature = "text_layout")]
835
    #[test]
836
    fn parse_font_fn_parses_the_positive_control() {
837
        let font_ref = parse_font_fn(loaded_source(MOCK_MONO.to_vec(), 0))
838
            .expect("the positive control must parse");
839
        let parsed = font_ref_to_parsed_font(&font_ref);
840

            
841
        assert_eq!(parsed.num_glyphs(), 96);
842
        assert_eq!(parsed.num_glyphs(), parsed.maxp_table.num_glyphs);
843
        assert_eq!(parsed.font_metrics.units_per_em, 1000);
844
        assert!(parsed.font_metrics.ascent > 0.0);
845
        assert!(parsed.font_metrics.descent <= 0.0);
846
        assert!(parsed.font_metrics.ascent.is_finite());
847
        assert!(parsed.font_metrics.descent.is_finite());
848
        assert!(parsed.font_metrics.line_gap.is_finite());
849
        assert_eq!(parsed.font_type, FontType::TrueType);
850
        assert_eq!(parsed.original_index, 0);
851
        assert!(parsed.cmap_subtable.is_some());
852
        assert_eq!(parsed.hash, parse_mock().hash);
853
    }
854

            
855
    /// `load_outlines` is not consulted by `parse_font_fn` (only `data` + `index`
856
    /// are). Both settings must therefore yield the same face — if this ever
857
    /// diverges, callers that flip the flag silently get a different font.
858
    #[cfg(feature = "text_layout")]
859
    #[test]
860
    fn parse_font_fn_ignores_the_load_outlines_flag() {
861
        let with = azul_core::resources::LoadedFontSource {
862
            data: azul_css::U8Vec::from_vec(MOCK_MONO.to_vec()),
863
            index: 0,
864
            load_outlines: true,
865
        };
866
        let without = azul_core::resources::LoadedFontSource {
867
            data: azul_css::U8Vec::from_vec(MOCK_MONO.to_vec()),
868
            index: 0,
869
            load_outlines: false,
870
        };
871
        let a = parse_font_fn(with).expect("parses with outlines");
872
        let b = parse_font_fn(without).expect("parses without outlines");
873
        let (pa, pb) = (font_ref_to_parsed_font(&a), font_ref_to_parsed_font(&b));
874
        assert_eq!(pa.hash, pb.hash);
875
        assert_eq!(pa.num_glyphs(), pb.num_glyphs());
876
        assert_eq!(pa.pdf_font_metrics, pb.pdf_font_metrics);
877
    }
878

            
879
    /// `index` is cast `u32 as usize` and fed to the table provider. Out-of-range
880
    /// face indices on a single-face font must be deterministic — no panic, no
881
    /// `12 + index * 4` overflow, and no face with a different glyph count.
882
    #[cfg(feature = "text_layout")]
883
    #[test]
884
    fn parse_font_fn_with_an_out_of_range_index_is_deterministic() {
885
        let baseline = parse_mock();
886
        for index in [1u32, 2, 0x7FFF_FFFF, u32::MAX - 1, u32::MAX] {
887
            if let Some(font_ref) = parse_font_fn(loaded_source(MOCK_MONO.to_vec(), index)) {
888
                let parsed = font_ref_to_parsed_font(&font_ref);
889
                assert_eq!(
890
                    parsed.num_glyphs(),
891
                    baseline.num_glyphs(),
892
                    "index {index} must not conjure a different face"
893
                );
894
                assert_eq!(parsed.original_index, index as usize);
895
            }
896
        }
897
    }
898

            
899
    /// Empty / garbage input on the failing path must not leak or corrupt state
900
    /// across repeated calls (the destructor is only installed on the `Some` path).
901
    #[cfg(feature = "text_layout")]
902
    #[test]
903
    fn parse_font_fn_failure_path_is_repeatable() {
904
        for _ in 0..200 {
905
            assert!(parse_font_fn(loaded_source(Vec::new(), 0)).is_none());
906
            assert!(parse_font_fn(loaded_source(vec![0xFF; 3], u32::MAX)).is_none());
907
        }
908
        // …and a good parse still works afterwards.
909
        assert!(parse_font_fn(loaded_source(MOCK_MONO.to_vec(), 0)).is_some());
910
    }
911

            
912
    /// Every successful parse mints a *fresh* identity, even for byte-identical
913
    /// input: `FontRef` equality is the never-reused `id`, not the heap pointer
914
    /// (freeing a font and reusing its address must not forge identity).
915
    #[cfg(feature = "text_layout")]
916
    #[test]
917
    fn parse_font_fn_mints_a_fresh_identity_per_call() {
918
        let a = parse_font_fn(loaded_source(MOCK_MONO.to_vec(), 0)).expect("parses");
919
        let b = parse_font_fn(loaded_source(MOCK_MONO.to_vec(), 0)).expect("parses");
920
        assert_ne!(
921
            a, b,
922
            "two parses of the same bytes are two distinct handles"
923
        );
924
        assert_ne!(a.id, b.id);
925
        assert!(b > a, "ids are monotonically assigned");
926
        // …but the *content* is identical.
927
        assert_eq!(
928
            font_ref_to_parsed_font(&a).hash,
929
            font_ref_to_parsed_font(&b).hash
930
        );
931
    }
932

            
933
    // ---------------------------------------------------------------
934
    // parsed_font_to_font_ref / font_ref_to_parsed_font  (round-trip)
935
    // ---------------------------------------------------------------
936

            
937
    /// encode == decode: wrapping a `ParsedFont` and reborrowing it must hand back
938
    /// the very same face, field for field.
939
    #[cfg(feature = "text_layout")]
940
    #[test]
941
    fn parsed_font_font_ref_round_trip_preserves_the_face() {
942
        let original = parse_mock();
943
        let expected_hash = original.hash;
944
        let expected_glyphs = original.num_glyphs();
945
        let expected_metrics = original.pdf_font_metrics;
946
        let expected_upem = original.font_metrics.units_per_em;
947
        let expected_ascent = original.font_metrics.ascent;
948
        let expected_type = original.font_type.clone();
949
        let expected_index = original.original_index;
950

            
951
        let font_ref = parsed_font_to_font_ref(original);
952
        let decoded = font_ref_to_parsed_font(&font_ref);
953

            
954
        assert_eq!(decoded.hash, expected_hash);
955
        assert_eq!(decoded.num_glyphs(), expected_glyphs);
956
        assert_eq!(decoded.pdf_font_metrics, expected_metrics);
957
        assert_eq!(decoded.font_metrics.units_per_em, expected_upem);
958
        assert!((decoded.font_metrics.ascent - expected_ascent).abs() < f32::EPSILON);
959
        assert_eq!(decoded.font_type, expected_type);
960
        assert_eq!(decoded.original_index, expected_index);
961
    }
962

            
963
    /// The freshly-minted handle's invariants: live pointer, refcount of exactly 1,
964
    /// destructor armed, non-zero id (id 0 flags a raw-reconstructed handle).
965
    #[cfg(feature = "text_layout")]
966
    #[test]
967
    fn parsed_font_to_font_ref_handle_invariants() {
968
        use core::sync::atomic::Ordering as AtomicOrdering;
969

            
970
        let font_ref = parsed_font_to_font_ref(parse_mock());
971
        assert!(!font_ref.parsed.is_null());
972
        assert!(!font_ref.copies.is_null());
973
        assert!(font_ref.run_destructor);
974
        assert_ne!(
975
            font_ref.id, 0,
976
            "id 0 is reserved for un-initialised handles"
977
        );
978
        assert_eq!(
979
            unsafe { (*font_ref.copies).load(AtomicOrdering::SeqCst) },
980
            1
981
        );
982
        assert_eq!(font_ref.get_parsed(), font_ref.parsed);
983
    }
984

            
985
    /// `font_ref_to_parsed_font` is a pure reborrow: repeated calls must yield the
986
    /// same address, and that address must be the handle's `parsed` pointer.
987
    #[cfg(feature = "text_layout")]
988
    #[test]
989
    fn font_ref_to_parsed_font_is_a_stable_reborrow() {
990
        use core::ffi::c_void;
991

            
992
        let font_ref = parsed_font_to_font_ref(parse_mock());
993
        let first: *const ParsedFont = font_ref_to_parsed_font(&font_ref);
994
        let second: *const ParsedFont = font_ref_to_parsed_font(&font_ref);
995
        assert!(core::ptr::eq(first, second), "reborrow must be stable");
996
        assert!(core::ptr::eq(first.cast::<c_void>(), font_ref.get_parsed()));
997
    }
998

            
999
    /// A clone shares the face (same pointer, same id) and bumps the refcount;
    /// dropping the clone must NOT free the face out from under the original.
    /// Reading through the survivor after the drop is the use-after-free probe.
    #[cfg(feature = "text_layout")]
    #[test]
    fn cloning_a_font_ref_shares_the_face_and_the_drop_is_refcounted() {
        use core::sync::atomic::Ordering as AtomicOrdering;
        let original = parsed_font_to_font_ref(parse_mock());
        let expected_hash = font_ref_to_parsed_font(&original).hash;
        let clone = original.clone();
        assert_eq!(clone.id, original.id, "a clone is the same font");
        assert_eq!(clone, original);
        assert!(core::ptr::eq(clone.parsed, original.parsed));
        assert_eq!(
            unsafe { (*original.copies).load(AtomicOrdering::SeqCst) },
            2
        );
        drop(clone);
        assert_eq!(
            unsafe { (*original.copies).load(AtomicOrdering::SeqCst) },
            1
        );
        assert_eq!(
            font_ref_to_parsed_font(&original).hash,
            expected_hash,
            "the face must survive its clone being dropped"
        );
        assert_eq!(font_ref_to_parsed_font(&original).num_glyphs(), 96);
    }
    /// Hammer the refcount: 1_000 clone/drop cycles (plus a batch held live at once)
    /// must leave the face readable and the count back at 1 — a double-decrement
    /// would free the `ParsedFont` early and turn the next reborrow into a UAF.
    #[cfg(feature = "text_layout")]
    #[test]
    fn font_ref_clone_drop_cycles_do_not_double_free() {
        use core::sync::atomic::Ordering as AtomicOrdering;
        let original = parsed_font_to_font_ref(parse_mock());
        let expected_hash = font_ref_to_parsed_font(&original).hash;
        for _ in 0..1_000 {
            let c = original.clone();
            assert_eq!(font_ref_to_parsed_font(&c).hash, expected_hash);
        }
        let batch: Vec<_> = (0..1_000).map(|_| original.clone()).collect();
        assert_eq!(
            unsafe { (*original.copies).load(AtomicOrdering::SeqCst) },
            1_001
        );
        drop(batch);
        assert_eq!(
            unsafe { (*original.copies).load(AtomicOrdering::SeqCst) },
            1
        );
        assert_eq!(font_ref_to_parsed_font(&original).hash, expected_hash);
    }
    /// Identity semantics as a hash/ordering key: clones collapse, independently
    /// wrapped faces don't — even when they hold byte-identical font data.
    #[cfg(feature = "text_layout")]
    #[test]
    fn font_ref_identity_is_per_handle_not_per_content() {
        use std::collections::{BTreeSet, HashSet};
        let a = parsed_font_to_font_ref(parse_mock());
        let b = parsed_font_to_font_ref(parse_mock());
        assert_ne!(a, b);
        assert!(a < b, "ids are monotonically assigned, so a precedes b");
        assert_eq!(
            font_ref_to_parsed_font(&a).hash,
            font_ref_to_parsed_font(&b).hash,
            "…even though the content hash is the same"
        );
        let set: HashSet<_> = vec![a.clone(), a.clone(), a.clone(), b.clone()]
            .into_iter()
            .collect();
        assert_eq!(set.len(), 2, "clones dedup, distinct handles do not");
        let ordered: BTreeSet<_> = vec![b.clone(), a.clone(), b.clone()].into_iter().collect();
        assert_eq!(ordered.len(), 2);
        assert_eq!(ordered.iter().next(), Some(&a));
    }
    /// Wrapping many faces in a row must keep every handle pointing at its *own*
    /// face — a shared/stale `Box::into_raw` would make them alias.
    #[cfg(feature = "text_layout")]
    #[test]
    fn many_font_refs_do_not_alias_each_other() {
        let refs: Vec<_> = (0..16)
            .map(|_| parsed_font_to_font_ref(parse_mock()))
            .collect();
        for (i, a) in refs.iter().enumerate() {
            assert_eq!(font_ref_to_parsed_font(a).num_glyphs(), 96);
            for b in refs.iter().skip(i + 1) {
                assert!(
                    !core::ptr::eq(a.parsed, b.parsed),
                    "independently boxed faces must not share a pointer"
                );
                assert_ne!(a.id, b.id);
            }
        }
    }
}