1
//! Resource management types for the application.
2
//!
3
//! This module contains the core types for managing application resources:
4
//! - `AppConfig`: application-level configuration (logging, fonts, routes, components)
5
//! - `ImageRef` / `ImageRefHash`: reference-counted decoded image handles
6
//! - `FontKey` / `FontInstanceKey` / `ImageKey`: renderer-scoped resource keys
7
//! - `RendererResources`: per-window font/image registry with frame-based GC
8
//! - `RawImage`: CPU-side pixel data with format conversion to BGRA8
9
//! - `build_add_font_resource_updates` / `build_add_image_resource_updates`: diff current frame
10
//!   against registered resources and produce WebRender updates
11

            
12
#[cfg(not(feature = "std"))]
13
use alloc::string::ToString;
14
use alloc::{boxed::Box, collections::btree_map::BTreeMap, string::String, vec::Vec};
15
use core::{
16
    fmt,
17
    hash::{Hash, Hasher},
18
    sync::atomic::{AtomicU64, AtomicUsize, Ordering as AtomicOrdering},
19
};
20

            
21
use azul_css::{
22
    codegen::format::GetHash,
23
    props::{
24
        basic::{
25
            pixel::DEFAULT_FONT_SIZE, ColorU, FloatValue, FontRef, LayoutRect, LayoutSize,
26
            StyleFontFamily, StyleFontFamilyVec, StyleFontSize,
27
        },
28
        style::scrollbar::OptionScrollPhysics,
29
    },
30
    system::SystemStyle,
31
    AzString, F32Vec, LayoutDebugMessage, OptionI32, StringVec, U16Vec, U32Vec, U8Vec,
32
};
33
use rust_fontconfig::FcFontCache;
34

            
35
// Re-export Core* callback types for public use
36
pub use crate::callbacks::{
37
    CoreImageCallback, CoreRenderImageCallback, CoreRenderImageCallbackType,
38
};
39
use crate::{
40
    callbacks::{LayoutCallback, VirtualViewCallback},
41
    dom::{DomId, NodeData, NodeType},
42
    geom::{LogicalPosition, LogicalRect, LogicalSize},
43
    gl::{OptionGlContextPtr, Texture},
44
    hit_test::DocumentId,
45
    id::NodeId,
46
    prop_cache::CssPropertyCache,
47
    refany::RefAny,
48
    styled_dom::{
49
        NodeHierarchyItemId, StyleFontFamiliesHash, StyleFontFamilyHash, StyledDom, StyledNodeState,
50
    },
51
    ui_solver::GlyphInstance,
52
    window::{AzStringPair, OptionChar, StringPairVec},
53
    xml::{
54
        ComponentDef, ComponentDefVec, ComponentId, ComponentLibrary, ComponentLibraryVec,
55
        ComponentSource, RegisterComponentFn, RegisterComponentLibraryFn,
56
    },
57
    FastBTreeSet, OrderedMap,
58
};
59

            
60
/// Selects which image layer of an element a node-image update applies to.
61
///
62
/// Used by `CallbackInfo::change_node_image` to distinguish between replacing an
63
/// element's CSS `background` image and replacing its main content image (e.g. an
64
/// animated GL texture re-rendered on resize).
65
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
66
#[repr(C)]
67
pub enum UpdateImageType {
68
    /// The update targets the element's background.
69
    Background,
70
    /// The update targets the element's main content.
71
    Content,
72
}
73

            
74
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
75
#[repr(C)]
76
pub struct DpiScaleFactor {
77
    pub inner: FloatValue,
78
}
79

            
80
impl DpiScaleFactor {
81
    #[must_use]
82
102
    pub fn new(f: f32) -> Self {
83
102
        Self {
84
102
            inner: FloatValue::new(f),
85
102
        }
86
102
    }
87
}
88

            
89
/// Determines what happens when all application windows are closed
90
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
91
#[repr(C)]
92
#[derive(Default)]
93
pub enum AppTerminationBehavior {
94
    /// Return control to `main()` when all windows are closed (if platform supports it).
95
    /// On macOS, this exits the `NSApplication` run loop and returns to `main()`.
96
    /// This is useful if you want to clean up resources or restart the event loop.
97
    ReturnToMain,
98
    /// Keep the application running even when all windows are closed.
99
    /// This is the standard macOS behavior (app stays in dock until explicitly quit).
100
    RunForever,
101
    /// Immediately terminate the process when all windows are closed.
102
    /// Calls `std::process::exit(0)`.
103
    #[default]
104
    EndProcess,
105
}
106

            
107
/// An email address, e.g. a support mailbox problem reports go to.
108
///
109
/// Deliberately a thin wrapper (no RFC 5322 validation): the address is
110
/// app-configured, not user input, and the SMTP layer reports a bad one
111
/// loudly at send time.
112
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
113
#[repr(C)]
114
pub struct EmailAddress {
115
    /// The address, e.g. `support@myapp.example`.
116
    pub address: AzString,
117
}
118

            
119
impl_option!(
120
    EmailAddress,
121
    OptionEmailAddress,
122
    copy = false,
123
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
124
);
125

            
126
impl EmailAddress {
127
    #[must_use]
128
1
    pub const fn new(address: AzString) -> Self {
129
1
        Self { address }
130
1
    }
131
}
132

            
133
/// Requested update behaviour.
134
///
135
/// The EFFECTIVE behaviour is this clamped by what the installation permits:
136
/// a package-managed binary (dpkg-owned, `/usr`, snap, flatpak,
137
/// `WindowsApps`) NEVER self-updates — `SelfUpdate` degrades to
138
/// `NotifyOnly` there ("update via your package manager").
139
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
140
#[repr(C)]
141
pub enum UpdateMode {
142
    /// Check, notify, and — after the user consents — download and swap the
143
    /// binary. Staging may happen in the background; INSTALLING never does.
144
    SelfUpdate,
145
    /// Check and notify only ("new version available"); installing is the
146
    /// user's / packager's job. The mode packagers should ship.
147
    #[default]
148
    NotifyOnly,
149
    /// Never check for updates.
150
    Disabled,
151
}
152

            
153
/// Update configuration, part of [`AppConfig`]. With `manifest_url` unset
154
/// every check reports an error naming this field — nothing phones home
155
/// unless the app points it somewhere.
156
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
157
#[repr(C)]
158
pub struct UpdateSettings {
159
    /// Requested behaviour; clamped by the detected install kind at runtime.
160
    pub mode: UpdateMode,
161
    /// URL of the update manifest (JSON: `{"latest": {"version", "download_url",
162
    /// "changelog_md", "digest"}}`). None = update checks disabled.
163
    pub manifest_url: azul_css::OptionString,
164
    /// The RUNNING version, compared against the manifest's `latest.version`
165
    /// (dotted-numeric compare). Apps typically pass `env!("CARGO_PKG_VERSION")`.
166
    pub current_version: AzString,
167
    /// Directory-safe application name; keys the updater's state directory
168
    /// (`{data_dir}/{app_name}/update-state.json`) and the staging area.
169
    pub app_name: AzString,
170
    /// RESERVED: the build's date, compiled in by the APP (e.g. a build
171
    /// script stamping `env!("BUILD_DATE")`). The engine only carries it —
172
    /// into telemetry resources, crash dumps and update checks.
173
    pub build_date: AzString,
174
    /// RESERVED: the build's VCS tag (or commit), compiled in by the APP.
175
    /// Same carriage as `build_date`.
176
    pub build_tag: AzString,
177
    /// The RELEASE CHANNEL this binary follows: `stable` (the default when
178
    /// empty), `beta`, `nightly`, or whatever names the publisher uses.
179
    /// Compiled in, so a nightly build cannot be talked onto the stable
180
    /// track by a manifest: the binary decides which channel it reads, the
181
    /// publisher decides what is in it.
182
    pub channel: AzString,
183
    /// Base64 minisign ROOT public key, compiled in by the APP. Non-empty
184
    /// arms the update SIGNATURE CHAIN: the manifest must then carry a
185
    /// root-signed signing-key statement and an artifact signature, and an
186
    /// unsigned release is a hard error instead of a fallback. Empty (the
187
    /// default) = digest verification only.
188
    pub root_public_key: AzString,
189
}
190

            
191
impl Default for UpdateSettings {
192
31
    fn default() -> Self {
193
31
        Self {
194
31
            mode: UpdateMode::default(),
195
31
            manifest_url: azul_css::OptionString::None,
196
31
            current_version: AzString::from_const_str("0.0.0"),
197
31
            app_name: AzString::from_const_str("azul-app"),
198
31
            build_date: AzString::from_const_str(""),
199
31
            build_tag: AzString::from_const_str(""),
200
31
            channel: AzString::from_const_str(""),
201
31
            root_public_key: AzString::from_const_str(""),
202
31
        }
203
31
    }
204
}
205

            
206
/// A named font bundled with the application (name + raw bytes).
207
/// The name is used to reference the font in CSS (e.g. `font-family: "MyFont"`).
208
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
209
#[repr(C)]
210
pub struct NamedFont {
211
    /// The font family name to use in CSS (e.g. "Roboto", "`MyCustomFont`")
212
    pub name: AzString,
213
    /// Raw font file bytes (TTF, OTF, etc.)
214
    pub bytes: U8Vec,
215
}
216

            
217
impl_option!(
218
    NamedFont,
219
    OptionNamedFont,
220
    copy = false,
221
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
222
);
223

            
224
impl NamedFont {
225
    #[must_use]
226
2
    pub const fn new(name: AzString, bytes: U8Vec) -> Self {
227
2
        Self { name, bytes }
228
2
    }
229
}
230

            
231
impl_vec!(
232
    NamedFont,
233
    NamedFontVec,
234
    NamedFontVecDestructor,
235
    NamedFontVecDestructorType,
236
    NamedFontVecSlice,
237
    OptionNamedFont
238
);
239
impl_vec_mut!(NamedFont, NamedFontVec);
240
impl_vec_debug!(NamedFont, NamedFontVec);
241
impl_vec_partialeq!(NamedFont, NamedFontVec);
242
impl_vec_eq!(NamedFont, NamedFontVec);
243
impl_vec_partialord!(NamedFont, NamedFontVec);
244
impl_vec_ord!(NamedFont, NamedFontVec);
245
impl_vec_hash!(NamedFont, NamedFontVec);
246
impl_vec_clone!(NamedFont, NamedFontVec, NamedFontVecDestructor);
247

            
248
/// Descriptor for a font that the layout engine currently has loaded in its
249
/// font cache.
250
///
251
/// Returned by `CallbackInfo::get_loaded_fonts()`. The `font_hash` field is
252
/// the same `u64` carried by `DisplayListItem::Text` glyph runs, so a callback
253
/// can correlate a loaded font with the text runs that use it and then fetch
254
/// the raw bytes via `CallbackInfo::get_loaded_font_bytes(font_hash)` (e.g. to
255
/// embed every font the layout actually used into a generated PDF).
256
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
257
#[repr(C)]
258
pub struct LoadedFont {
259
    /// Stable hash of the parsed font, identical to the `font_hash` stored on
260
    /// `DisplayListItem::Text` glyph runs. Use this to look up the bytes with
261
    /// `CallbackInfo::get_loaded_font_bytes`.
262
    pub font_hash: u64,
263
    /// PostScript / family name from the font's `name` table, or an empty
264
    /// string if the font did not provide one.
265
    pub family_name: AzString,
266
    /// Total number of glyphs in the font (from the `maxp` table).
267
    pub num_glyphs: u32,
268
    /// `true` if the source font bytes are retained and can be retrieved with
269
    /// `CallbackInfo::get_loaded_font_bytes(font_hash)`. Fonts loaded on the
270
    /// production (lazy mmap) path retain their bytes; some test-only fonts do
271
    /// not.
272
    pub has_bytes: bool,
273
}
274

            
275
impl_option!(
276
    LoadedFont,
277
    OptionLoadedFont,
278
    copy = false,
279
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
280
);
281

            
282
impl LoadedFont {
283
    #[must_use]
284
2
    pub const fn new(
285
2
        font_hash: u64,
286
2
        family_name: AzString,
287
2
        num_glyphs: u32,
288
2
        has_bytes: bool,
289
2
    ) -> Self {
290
2
        Self {
291
2
            font_hash,
292
2
            family_name,
293
2
            num_glyphs,
294
2
            has_bytes,
295
2
        }
296
2
    }
297
}
298

            
299
impl_vec!(
300
    LoadedFont,
301
    LoadedFontVec,
302
    LoadedFontVecDestructor,
303
    LoadedFontVecDestructorType,
304
    LoadedFontVecSlice,
305
    OptionLoadedFont
306
);
307
impl_vec_mut!(LoadedFont, LoadedFontVec);
308
impl_vec_debug!(LoadedFont, LoadedFontVec);
309
impl_vec_partialeq!(LoadedFont, LoadedFontVec);
310
impl_vec_eq!(LoadedFont, LoadedFontVec);
311
impl_vec_partialord!(LoadedFont, LoadedFontVec);
312
impl_vec_ord!(LoadedFont, LoadedFontVec);
313
impl_vec_hash!(LoadedFont, LoadedFontVec);
314
impl_vec_clone!(LoadedFont, LoadedFontVec, LoadedFontVecDestructor);
315
#[allow(variant_size_differences)]
316
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
317
// disparity accepted
318
/// Configuration for how fonts should be loaded at app startup.
319
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
320
#[repr(C, u8)]
321
#[derive(Default)]
322
pub enum FontLoadingConfig {
323
    /// Load all system fonts (default behavior, can be slow on systems with many fonts)
324
    #[default]
325
    LoadAllSystemFonts,
326
    /// Only load fonts for specific families (faster startup).
327
    /// Generic families like "sans-serif" are automatically expanded to OS-specific fonts.
328
    LoadOnlyFamilies(StringVec),
329
    /// Don't load any system fonts, only use bundled fonts
330
    BundledFontsOnly,
331
}
332

            
333
/// Mock environment for CSS evaluation.
334
///
335
/// Allows overriding auto-detected system properties for testing and development.
336
/// Any field set to `None` will use the auto-detected value.
337
/// Any field set to `Some(...)` will override the auto-detected value.
338
///
339
/// # Example
340
/// ```rust
341
/// # use azul_core::resources::CssMockEnvironment;
342
/// use azul_css::dynamic_selector::{
343
///     OptionOsCondition, OptionOsVersion, OptionThemeCondition, OsCondition, OsVersion,
344
///     ThemeCondition,
345
/// };
346
///
347
/// // Mock a Linux dark theme environment on any platform
348
/// let mock = CssMockEnvironment {
349
///     os: OptionOsCondition::Some(OsCondition::Linux),
350
///     theme: OptionThemeCondition::Some(ThemeCondition::Dark),
351
///     ..Default::default()
352
/// };
353
///
354
/// // Mock Windows XP for retro testing
355
/// let mock = CssMockEnvironment {
356
///     os: OptionOsCondition::Some(OsCondition::Windows),
357
///     os_version: OptionOsVersion::Some(OsVersion::WIN_XP),
358
///     ..Default::default()
359
/// };
360
/// ```
361
#[derive(Debug, Clone, Default)]
362
#[repr(C)]
363
pub struct CssMockEnvironment {
364
    /// Override the current theme (light/dark)
365
    pub theme: azul_css::dynamic_selector::OptionThemeCondition,
366
    /// Override the current language (BCP 47 tag, e.g., "de-DE", "en-US")
367
    pub language: azul_css::OptionString,
368
    /// Override the detected OS version
369
    pub os_version: azul_css::dynamic_selector::OptionOsVersion,
370
    /// Override the detected operating system
371
    pub os: azul_css::dynamic_selector::OptionOsCondition,
372
    /// Override the Linux desktop environment (only applies when os = Linux)
373
    pub desktop_env: azul_css::dynamic_selector::OptionLinuxDesktopEnv,
374
    /// Override viewport dimensions (for @media queries)
375
    /// Only use for testing - normally set by window size
376
    pub viewport_width: azul_css::OptionF32,
377
    pub viewport_height: azul_css::OptionF32,
378
    /// Override the reduced motion preference
379
    pub prefers_reduced_motion: azul_css::OptionBool,
380
    /// Override the high contrast preference
381
    pub prefers_high_contrast: azul_css::OptionBool,
382
}
383

            
384
impl CssMockEnvironment {
385
    /// Create a mock for Linux environment
386
    #[must_use]
387
2
    pub fn linux() -> Self {
388
2
        Self {
389
2
            os: azul_css::dynamic_selector::OptionOsCondition::Some(
390
2
                azul_css::dynamic_selector::OsCondition::Linux,
391
2
            ),
392
2
            ..Default::default()
393
2
        }
394
2
    }
395

            
396
    /// Create a mock for Windows environment
397
    #[must_use]
398
2
    pub fn windows() -> Self {
399
2
        Self {
400
2
            os: azul_css::dynamic_selector::OptionOsCondition::Some(
401
2
                azul_css::dynamic_selector::OsCondition::Windows,
402
2
            ),
403
2
            ..Default::default()
404
2
        }
405
2
    }
406

            
407
    /// Create a mock for macOS environment
408
    #[must_use]
409
1
    pub fn macos() -> Self {
410
1
        Self {
411
1
            os: azul_css::dynamic_selector::OptionOsCondition::Some(
412
1
                azul_css::dynamic_selector::OsCondition::MacOS,
413
1
            ),
414
1
            ..Default::default()
415
1
        }
416
1
    }
417

            
418
    /// Create a mock for dark theme
419
    #[must_use]
420
3
    pub fn dark_theme() -> Self {
421
3
        Self {
422
3
            theme: azul_css::dynamic_selector::OptionThemeCondition::Some(
423
3
                azul_css::dynamic_selector::ThemeCondition::Dark,
424
3
            ),
425
3
            ..Default::default()
426
3
        }
427
3
    }
428

            
429
    /// Create a mock for light theme
430
    #[must_use]
431
1
    pub fn light_theme() -> Self {
432
1
        Self {
433
1
            theme: azul_css::dynamic_selector::OptionThemeCondition::Some(
434
1
                azul_css::dynamic_selector::ThemeCondition::Light,
435
1
            ),
436
1
            ..Default::default()
437
1
        }
438
1
    }
439

            
440
    /// Apply this mock to a `DynamicSelectorContext`
441
3
    pub fn apply_to(&self, ctx: &mut azul_css::dynamic_selector::DynamicSelectorContext) {
442
3
        if let azul_css::dynamic_selector::OptionOsCondition::Some(os) = self.os {
443
2
            ctx.os = os;
444
2
        }
445
3
        if let azul_css::dynamic_selector::OptionOsVersion::Some(os_version) = self.os_version {
446
            ctx.os_version = os_version;
447
3
        }
448
3
        if let azul_css::dynamic_selector::OptionLinuxDesktopEnv::Some(de) = self.desktop_env {
449
            ctx.desktop_env = azul_css::dynamic_selector::OptionLinuxDesktopEnv::Some(de);
450
3
        }
451
3
        if let azul_css::dynamic_selector::OptionThemeCondition::Some(ref theme) = self.theme {
452
2
            ctx.theme = theme.clone();
453
2
        }
454
3
        if let azul_css::OptionString::Some(ref lang) = self.language {
455
2
            ctx.language = lang.clone();
456
2
        }
457
3
        if let azul_css::OptionBool::Some(reduced) = self.prefers_reduced_motion {
458
2
            ctx.prefers_reduced_motion = if reduced {
459
2
                azul_css::dynamic_selector::BoolCondition::True
460
            } else {
461
                azul_css::dynamic_selector::BoolCondition::False
462
            };
463
1
        }
464
3
        if let azul_css::OptionBool::Some(high_contrast) = self.prefers_high_contrast {
465
2
            ctx.prefers_high_contrast = if high_contrast {
466
                azul_css::dynamic_selector::BoolCondition::True
467
            } else {
468
2
                azul_css::dynamic_selector::BoolCondition::False
469
            };
470
1
        }
471
3
        if let azul_css::OptionF32::Some(w) = self.viewport_width {
472
2
            ctx.viewport_width = w;
473
2
        }
474
3
        if let azul_css::OptionF32::Some(h) = self.viewport_height {
475
2
            ctx.viewport_height = h;
476
2
        }
477
3
    }
478
}
479

            
480
impl_option!(
481
    CssMockEnvironment,
482
    OptionCssMockEnvironment,
483
    copy = false,
484
    [Debug, Clone]
485
);
486

            
487
/// A route mapping a URL pattern to a layout callback.
488
///
489
/// Routes are cross-platform: on desktop, switching routes swaps the
490
/// active layout callback and triggers `RefreshDom`. On web, it also
491
/// calls `history.pushState()` for browser navigation.
492
///
493
/// # Pattern syntax
494
///
495
/// - `"/"` — exact root
496
/// - `"/about"` — exact path
497
/// - `"/user/:id"` — parameterized segment, `/user/42` yields `id = "42"`
498
///
499
/// # C API
500
/// ```c
501
/// AzAppConfig_addRoute(&config, AzString_fromConstStr("/user/:id"), layout_user);
502
/// ```
503
#[repr(C)]
504
pub struct Route {
505
    /// URL pattern (e.g. `"/"`, `"/about"`, `"/user/:id"`)
506
    pub pattern: AzString,
507
    /// Layout callback invoked when this route is active
508
    pub layout_callback: LayoutCallback,
509
}
510

            
511
impl Clone for Route {
512
    fn clone(&self) -> Self {
513
        Self {
514
            pattern: self.pattern.clone(),
515
            layout_callback: self.layout_callback.clone(),
516
        }
517
    }
518
}
519
impl fmt::Debug for Route {
520
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521
        f.debug_struct("Route")
522
            .field("pattern", &self.pattern)
523
            .field("layout_callback", &self.layout_callback)
524
            .finish()
525
    }
526
}
527
impl PartialEq for Route {
528
    fn eq(&self, o: &Self) -> bool {
529
        self.pattern == o.pattern && self.layout_callback == o.layout_callback
530
    }
531
}
532
impl Eq for Route {}
533
impl PartialOrd for Route {
534
    fn partial_cmp(&self, o: &Self) -> Option<core::cmp::Ordering> {
535
        Some(self.cmp(o))
536
    }
537
}
538
impl Ord for Route {
539
    fn cmp(&self, o: &Self) -> core::cmp::Ordering {
540
        self.pattern
541
            .cmp(&o.pattern)
542
            .then_with(|| self.layout_callback.cmp(&o.layout_callback))
543
    }
544
}
545
impl Hash for Route {
546
    fn hash<H: Hasher>(&self, state: &mut H) {
547
        self.pattern.hash(state);
548
        self.layout_callback.hash(state);
549
    }
550
}
551

            
552
impl_option!(
553
    Route,
554
    OptionRoute,
555
    copy = false,
556
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
557
);
558
impl_vec!(
559
    Route,
560
    RouteVec,
561
    RouteVecDestructor,
562
    RouteVecDestructorType,
563
    RouteVecSlice,
564
    OptionRoute
565
);
566
impl_vec_mut!(Route, RouteVec);
567
impl_vec_debug!(Route, RouteVec);
568
impl_vec_clone!(Route, RouteVec, RouteVecDestructor);
569
impl_vec_partialeq!(Route, RouteVec);
570
impl_vec_eq!(Route, RouteVec);
571
impl_vec_partialord!(Route, RouteVec);
572
impl_vec_ord!(Route, RouteVec);
573
impl_vec_hash!(Route, RouteVec);
574

            
575
/// Result of matching a URL against a route pattern.
576
///
577
/// Stores the matched pattern and any extracted parameters.
578
/// Available to layout callbacks via `LayoutCallbackInfo::get_route_param()`.
579
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
580
#[repr(C)]
581
pub struct RouteMatch {
582
    /// The matched route pattern (e.g. `"/user/:id"`)
583
    pub pattern: AzString,
584
    /// Extracted parameters (e.g. `[("id", "42")]`)
585
    pub params: StringPairVec,
586
}
587

            
588
impl RouteMatch {
589
    /// Get a route parameter by key.
590
    #[must_use]
591
83
    pub fn get_param(&self, key: &str) -> Option<&AzString> {
592
83
        self.params.get_key(key)
593
83
    }
594
}
595

            
596
impl_option!(
597
    RouteMatch,
598
    OptionRouteMatch,
599
    copy = false,
600
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
601
);
602

            
603
/// Match a URL path against a route pattern, extracting parameters.
604
///
605
/// Returns `Some(RouteMatch)` with extracted params on match, `None` otherwise.
606
///
607
/// # Examples
608
/// - pattern `"/user/:id"`, path `"/user/42"` → `Some(RouteMatch { params: [("id","42")] })`
609
/// - pattern `"/"`, path `"/"` → `Some(RouteMatch { params: [] })`
610
/// - pattern `"/about"`, path `"/settings"` → `None`
611
#[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
612
#[must_use]
613
96
pub fn match_route(pattern: &str, path: &str) -> Option<RouteMatch> {
614
20245
    let pat_segs: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
615
20193
    let path_segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
616

            
617
96
    if pat_segs.len() != path_segs.len() {
618
41
        return None;
619
55
    }
620

            
621
55
    let mut params = Vec::new();
622
20061
    for (pat, val) in pat_segs.iter().zip(path_segs.iter()) {
623
20061
        if let Some(param_name) = pat.strip_prefix(':') {
624
10028
            params.push(AzStringPair {
625
10028
                key: AzString::from(param_name.to_string()),
626
10028
                value: AzString::from((*val).to_string()),
627
10028
            });
628
10033
        } else if pat != val {
629
12
            return None;
630
10021
        }
631
    }
632

            
633
43
    Some(RouteMatch {
634
43
        pattern: AzString::from(pattern.to_string()),
635
43
        params: StringPairVec::from_vec(params),
636
43
    })
637
96
}
638

            
639
/// The ZOMBIE-SPECIFIC half of what a native animation function receives.
640
///
641
/// The other half is a full [`TimerCallbackInfo`] (USER ruling 2026-08-17),
642
/// so a callback can also reach the LIVE dom, queue changes, read momentum,
643
/// measure any node… full customizability, not a keyhole.
644
///
645
/// The pointers here are BORROWED for the duration of the call — a function
646
/// may walk the retained tree (e.g. measure its own component's text
647
/// mid-exit) but must not store them: for an exit the tree is the retained
648
/// zombie frame, freed when the animation completes.
649
#[derive(Debug, Clone, Copy)]
650
#[repr(C)]
651
pub struct ZombieAnimInfo {
652
    /// The `StyledDom` the ANIMATED node lives in — the retained tree for
653
    /// exits, the live tree for enters. Never null during a call. (The live
654
    /// dom is separately reachable through the `TimerCallbackInfo`.)
655
    pub styled_dom: *const crate::styled_dom::StyledDom,
656
    /// The animated node's index in THAT tree.
657
    pub node_id: u64,
658
    /// The node's rect in logical px: the retained rect for exits, the
659
    /// solved rect for enters.
660
    pub rect: LogicalRect,
661
    /// The viewport the tree was laid out in.
662
    pub viewport: LogicalRect,
663
    pub dpi_factor: f32,
664
    /// RAW LINEAR progress 0..=1. The engine does NOT pre-apply easing for
665
    /// native functions: the DECLARED timing arrives in `timing` below, and
666
    /// the callback owns the math — apply it via `AnimationTiming::evaluate`
667
    /// or substitute its own curve entirely.
668
    pub t: f32,
669
    /// The timing the CSS requested (`ease`, `spring`, a
670
    /// `cubic-bezier(...)` point list, …).
671
    pub timing: azul_css::props::basic::animation::AnimationTiming,
672
    /// The animation's velocity ENTERING this frame, logical px/s — the
673
    /// derivative of the previous two samples (one-frame lag; zero on the
674
    /// first frame and for enter/live tracks today). The read half of the
675
    /// momentum API for native functions: reversing with continuity means
676
    /// producing frames that start at this speed.
677
    pub velocity_x: f32,
678
    pub velocity_y: f32,
679
}
680

            
681
/// One frame of a native presence animation, returned by a
682
/// the zombie animation callback. Absolute values, not deltas.
683
#[derive(Debug, Clone, Copy, PartialEq)]
684
#[repr(C)]
685
pub struct ZombieFrame {
686
    /// Translation in logical px, applied about the node's origin.
687
    pub translate_x: f32,
688
    pub translate_y: f32,
689
    /// 0.0 skips the node entirely this frame.
690
    pub opacity: f32,
691
    /// Absolute painted width in logical px (left-anchored narrowing for
692
    /// exits; the live layout already owns the vacated space). `None` keeps
693
    /// the full width. Ignored for enters (live width is layout's job).
694
    pub width: azul_css::OptionF32,
695
    /// Clip the exit to its frozen rect so the motion cannot paint over
696
    /// neighbouring components. Ignored for enters.
697
    pub clip_to_frozen_rect: bool,
698
}
699

            
700
impl Default for ZombieFrame {
701
    fn default() -> Self {
702
        Self {
703
            translate_x: 0.0,
704
            translate_y: 0.0,
705
            opacity: 1.0,
706
            width: azul_css::OptionF32::None,
707
            clip_to_frozen_rect: true,
708
        }
709
    }
710
}
711

            
712
// TYPE-ERASED `extern "C"` entry point of a native presence animation:
713
// stored as `usize` for the same reason as `crate::callbacks::CoreCallback` —
714
// the REAL signature takes a `&mut TimerCallbackInfo` (full live-dom access,
715
// USER ruling 2026-08-17), and that type lives in `azul-layout`, above this
716
// crate. azul-layout defines the typed alias and casts on invocation:
717
// `extern "C" fn(&mut RefAny, &mut TimerCallbackInfo, &ZombieAnimInfo) -> ZombieFrame`
718
// (Erased alias removed: the PUBLIC `ZombieAnimCallbackType` name now
719
// belongs to the GENERATED typed fn-pointer emitted from `ZombieAnimCallback`'s
720
// callback_typedef in api.json — two same-name exports collided in codegen.
721
// Internally the erasure is just `usize`.)
722

            
723
/// The type-erased component animation callback (a fn pointer as `usize`).
724
#[repr(C)]
725
#[derive(Clone, Copy)]
726
pub struct ZombieAnimCallback {
727
    pub cb: usize,
728
}
729

            
730
impl fmt::Debug for ZombieAnimCallback {
731
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732
        write!(f, "ZombieAnimCallback @ 0x{:x}", self.cb)
733
    }
734
}
735
impl Hash for ZombieAnimCallback {
736
    fn hash<H: Hasher>(&self, state: &mut H) {
737
        state.write_usize(self.cb);
738
    }
739
}
740
impl PartialEq for ZombieAnimCallback {
741
    fn eq(&self, other: &Self) -> bool {
742
        self.cb == other.cb
743
    }
744
}
745
impl Eq for ZombieAnimCallback {}
746
impl PartialOrd for ZombieAnimCallback {
747
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
748
        Some(self.cmp(other))
749
    }
750
}
751
impl Ord for ZombieAnimCallback {
752
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
753
        self.cb.cmp(&other.cb)
754
    }
755
}
756

            
757
/// A COMPONENT-ATTACHED native animation function.
758
///
759
/// Lives on the node's own `NodeData` (USER ruling 2026-08-17 — a sidebar
760
/// widget ships its fly-out next to its own DOM, not in app-global state;
761
/// the global `AppConfig` registry this replaced was "a bit unclean").
762
/// Resolvable by NAME from that node's `-azul-animation-in` /
763
/// `-azul-animation-out`, AFTER stylesheet `@keyframes` — the web mechanism
764
/// stays the only default name source.
765
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
766
#[repr(C)]
767
pub struct AnimationFunction {
768
    pub name: AzString,
769
    pub callback: ZombieAnimCallback,
770
    /// Passed to `callback` on every invocation.
771
    pub data: RefAny,
772
}
773

            
774
/// Configuration of the SYSTEM-driven animations: physics-based scrolling
775
/// and the caret / selection tweens. Lives on [`AppConfig`] so a platform or
776
/// application can tune the feel without rebuilding azul.
777
///
778
/// The scroll physics override is applied ON TOP of the platform-discovered
779
/// [`SystemStyle`] at `App::create` time (`None` keeps the per-platform
780
/// preset). The tween slots always apply; set a duration to `0` to disable
781
/// that tween (the caret / selection then jumps, the classic behavior).
782
#[derive(Debug, Clone)]
783
#[repr(C)]
784
pub struct SystemAnimations {
785
    // Field order: decreasing alignment (8-aligned callbacks/RefAny first,
786
    // then the 4-aligned option/durations, bool last) — the autofix padding
787
    // lint enforces this, and the api.json struct_fields order must match
788
    // (the field-order lint enforces THAT).
789
    /// The caret tween MATH: called every animation frame with the past /
790
    /// current caret rectangles and linear progress `t`; returns the
791
    /// rectangle to render. Default: ease-out cubic lerp.
792
    pub caret_tween: crate::callbacks::CaretTweenCallback,
793
    /// The selection tween MATH: called every animation frame with the
794
    /// past / current selection band rectangles and linear progress `t`;
795
    /// returns the rectangles to render (must match the current count).
796
    /// Default: ease-out cubic lerp, rectangles paired by index.
797
    pub selection_tween: crate::callbacks::SelectionTweenCallback,
798
    /// User data passed to `caret_tween` on every invocation.
799
    pub caret_tween_data: RefAny,
800
    /// User data passed to `selection_tween` on every invocation.
801
    pub selection_tween_data: RefAny,
802

            
803
    /// Overrides `SystemStyle.scroll_physics` (momentum, overscroll /
804
    /// rubber-band, wheel-vs-trackpad curves). `None` = platform default.
805
    pub scroll_physics: OptionScrollPhysics,
806
    /// Duration of the caret-move tween in ms. `0` disables the tween.
807
    /// While the tween runs, caret blinking is suppressed (caret stays
808
    /// solid while it moves).
809
    pub caret_tween_duration_ms: u32,
810
    /// Duration of the selection tween in ms. `0` disables the tween.
811
    pub selection_tween_duration_ms: u32,
812
    /// Focus-ring glide duration in ms (ledger #29). `0` (the DEFAULT)
813
    /// disables the ring entirely — no visual change for existing apps;
814
    /// an app that opts in gets a focus outline that GLIDES between
815
    /// focused elements using the `caret_tween` interpolator (the ring is
816
    /// suppressed while a text-editing session owns focus — there the
817
    /// caret is the indicator).
818
    pub focus_ring_duration_ms: u32,
819
    /// Whether "scroll the caret into view" glides via the scroll-physics
820
    /// spring (true, the Word feel) or jumps instantly (false — also what
821
    /// [`Self::disabled`] sets, keeping e2e screenshots deterministic).
822
    pub caret_scroll_glide: bool,
823
}
824

            
825
impl SystemAnimations {
826
    /// All system animations disabled: no scroll-physics override, tween
827
    /// durations 0 (caret / selection jump). Test drivers and deterministic
828
    /// harnesses use this so screenshots never catch geometry mid-glide.
829
    #[must_use]
830
666
    pub fn disabled() -> Self {
831
666
        Self {
832
666
            caret_tween_duration_ms: 0,
833
666
            selection_tween_duration_ms: 0,
834
666
            caret_scroll_glide: false,
835
666
            focus_ring_duration_ms: 0,
836
666
            ..Self::default()
837
666
        }
838
666
    }
839
}
840

            
841
impl Default for SystemAnimations {
842
1141
    fn default() -> Self {
843
1141
        Self {
844
1141
            scroll_physics: OptionScrollPhysics::None,
845
1141
            // Barely noticeable by design (user directive): a short glide,
846
1141
            // not an animation the eye waits for.
847
1141
            caret_tween_duration_ms: 60,
848
1141
            caret_tween: crate::callbacks::CaretTweenCallback::create(
849
1141
                crate::callbacks::default_caret_tween,
850
1141
            ),
851
1141
            caret_tween_data: RefAny::new(()),
852
1141
            selection_tween_duration_ms: 60,
853
1141
            selection_tween: crate::callbacks::SelectionTweenCallback::create(
854
1141
                crate::callbacks::default_selection_tween,
855
1141
            ),
856
1141
            selection_tween_data: RefAny::new(()),
857
1141
            caret_scroll_glide: true,
858
1141
            // ON by default: keyboard focus MUST be visible, or Tab-navigating
859
1141
            // an app is indistinguishable from Tab doing nothing (device
860
1141
            // report, 2026-08-31 - focus and Enter/Space activation both
861
1141
            // worked, but nothing on screen said which control had focus).
862
1141
            // W3C/UA behaviour is to draw a focus indicator even with no
863
1141
            // author CSS. A short glide, like the caret tween; `disabled()`
864
1141
            // still zeroes it so e2e screenshots stay deterministic.
865
1141
            focus_ring_duration_ms: 60,
866
1141
        }
867
1141
    }
868
}
869

            
870
/// Configuration for optional features, such as whether to enable logging or panic hooks
871
#[derive(Debug, Clone)]
872
#[repr(C)]
873
pub struct AppConfig {
874
    /// If enabled, logs error and info messages.
875
    ///
876
    /// Default is `LevelFilter::Error` to log all errors by default
877
    pub log_level: AppLogLevel,
878
    /// NATURAL SCROLLING (9b-ii-b-i-a; USER RULING 2026-09-04: a field here,
879
    /// default off, the app enables it or loads the system's setting).
880
    ///
881
    /// The engine's own scroll sign: `Disabled` never flips a delta, `Enabled`
882
    /// flips every wheel / trackpad delta (in-app natural scrolling regardless
883
    /// of the OS), `System` reads the platform's preference at startup and
884
    /// keeps it readable (`CallbackInfo::get_natural_scroll`) - WITHOUT a
885
    /// second flip, because every desktop platform already applies the user's
886
    /// preference to the deltas it hands over (macOS, the Windows precision
887
    /// touchpad, libinput on Wayland and X11); flipping again would undo it.
888
    /// Where the platform reports nothing the answer is unknown and `System`
889
    /// behaves as `Disabled`.
890
    pub natural_scroll: NaturalScroll,
891
    /// If the app crashes / panics, a window with a message box pops up.
892
    /// Setting this to `false` disables the popup box.
893
    pub enable_visual_panic_hook: bool,
894
    /// If this is set to `true` (the default), a backtrace + error information
895
    /// gets logged to stdout and the logging file (only if logging is enabled).
896
    pub enable_logging_on_panic: bool,
897
    /// Whether Ctrl+wheel is synthesized into a pinch gesture. Default `true`.
898
    ///
899
    /// A Windows PRECISION TOUCHPAD does not deliver pinch through
900
    /// `WM_GESTURE` - that message is the touchSCREEN path. A touchpad reports
901
    /// pinch as Ctrl+`WM_MOUSEWHEEL`, which is the same thing every browser
902
    /// zooms on, so synthesizing a pinch from it is what makes pinch-to-zoom
903
    /// work on the overwhelming majority of Windows laptops.
904
    ///
905
    /// The cost of that is a real MOUSE with a real Ctrl key produces the same
906
    /// message, and cannot be told apart from a touchpad at this layer - so an
907
    /// app where Ctrl+wheel means something else (a CAD zoom step, a font-size
908
    /// nudge) receives a pinch it did not want. Setting this to `false` turns
909
    /// the synthesis off and leaves Ctrl+wheel as a plain wheel event with the
910
    /// Ctrl modifier set, which such an app can read directly.
911
    ///
912
    /// Ignored on every platform but Windows: macOS and Wayland report real
913
    /// pinch gestures, so nothing has to be inferred there.
914
    pub synthesize_pinch_from_ctrl_wheel: bool,
915
    /// Whether the app publishes itself to the OS as a media player.
916
    /// Default `false`.
917
    ///
918
    /// On Linux the desktop environment usually GRABS the media keys, so
919
    /// `XF86AudioPlay` and friends never reach the application as keysyms at
920
    /// all (the 9h-i table only sees them when nothing grabbed them). The
921
    /// transport in that case is MPRIS over D-Bus: the desktop calls
922
    /// `Play`/`Pause`/`Next` on whatever players are registered, and azul
923
    /// turns those calls back into ordinary `VirtualKeyCode` presses.
924
    ///
925
    /// OFF by default because registering has a VISIBLE side effect: the app
926
    /// appears in the desktop's media controls (GNOME's system menu, KDE's
927
    /// media applet) as a player. That is correct for a music app and wrong
928
    /// for a text editor, and no engine-side signal distinguishes them - so
929
    /// the app says which it is.
930
    ///
931
    /// macOS is the same bargain under a different name: `MPRemoteCommandCenter`
932
    /// delivers the media keys, but only to the app the system considers "now
933
    /// playing", so registering puts the app in Control Center and the Now
934
    /// Playing widget.
935
    ///
936
    /// Ignored on Windows, which delivers media keys as `WM_APPCOMMAND` to the
937
    /// focused window and publishes nothing.
938
    pub expose_system_media_controls: bool,
939
    /// Determines what happens when all windows are closed.
940
    /// Default: `EndProcess` (terminate when last window closes).
941
    pub termination_behavior: AppTerminationBehavior,
942
    /// Icon provider for the application.
943
    /// Register icons here before calling `App::run()`.
944
    /// Each window will clone this provider (cheap, Arc-based).
945
    pub icon_provider: crate::icon::IconProviderHandle,
946
    /// Fonts bundled with the application.
947
    /// These fonts are loaded into memory and take priority over system fonts.
948
    pub bundled_fonts: NamedFontVec,
949
    /// Configuration for how system fonts should be loaded.
950
    /// Default: `LoadAllSystemFonts` (scan all system fonts at startup)
951
    pub font_loading: FontLoadingConfig,
952
    /// Optional mock environment for CSS evaluation.
953
    ///
954
    /// When set, this overrides the auto-detected system properties (OS, theme, etc.)
955
    /// for CSS @-rules and dynamic selectors. This is useful for:
956
    /// - Testing OS-specific styles on a different platform
957
    /// - Screenshot testing with consistent environment
958
    /// - Previewing how the app looks on different systems
959
    ///
960
    /// Default: None (use auto-detected system properties)
961
    pub mock_css_environment: OptionCssMockEnvironment,
962
    /// System style detected at startup (theme, colors, fonts, etc.)
963
    ///
964
    /// This is detected once at `AppConfig::create()` and passed to all windows.
965
    /// You can override this after creation to use a custom system style,
966
    /// for example to test how your app looks on a different platform.
967
    pub system_style: SystemStyle,
968
    /// Component libraries registered at startup.
969
    ///
970
    /// Use `add_component()` to register individual components, or
971
    /// `add_component_library()` to register entire libraries.
972
    /// User-registered (and built-in) component libraries.
973
    ///
974
    /// The 52 built-in HTML elements are automatically registered by
975
    /// `AppConfig::create()` via `register_builtin_components`.
976
    /// Additional libraries can be added with `add_component_library`.
977
    pub component_libraries: ComponentLibraryVec,
978
    /// Registered routes mapping URL patterns to layout callbacks.
979
    ///
980
    /// Cross-platform: on desktop, the active route determines which layout
981
    /// callback runs. On web, routes map to HTTP endpoints and browser URLs.
982
    ///
983
    /// The first route (or `"/"`) is the default. Use `add_route()` to register.
984
    pub routes: RouteVec,
985
    /// System-animation configuration (scroll physics override, caret /
986
    /// selection tween hooks). See [`SystemAnimations`].
987
    pub system_animations: SystemAnimations,
988
    /// Handler for E2E ops the engine does not implement, letting a scenario
989
    /// drive application-level actions ("now load the document") that the
990
    /// engine cannot express on the app's behalf.
991
    ///
992
    /// The default recognises nothing, so a scenario naming a custom op fails
993
    /// unless the app installed a handler.
994
    pub custom_e2e_op: crate::events::CustomE2eOpCallback,
995
    /// Update configuration: manifest URL, requested mode, the running
996
    /// version. Drives `CallbackInfo::check_for_updates` and the
997
    /// `SysDialogType::UpdateVersion` dialog. Default: no manifest (checks
998
    /// disabled), `NotifyOnly`.
999
    pub updates: UpdateSettings,
    /// URL of the app's changelog in Markdown. The `UpdateVersion` dialog
    /// shows it before installing when a release carries no changelog link
    /// of its own.
    pub changelog_md: azul_css::OptionString,
    /// Support mailbox that problem reports (`SysDialogType::ReportProblem`)
    /// and manual crash reports go to. None = the `ReportProblem` dialog saves
    /// reports to disk instead of mailing them.
    pub report_problem: OptionEmailAddress,
}
impl AppConfig {
    #[must_use]
31
    pub fn create() -> Self {
31
        let log_level = AppLogLevel::Error;
31
        let icon_provider = crate::icon::IconProviderHandle::new();
31
        let bundled_fonts = NamedFontVec::from_const_slice(&[]);
31
        let font_loading = FontLoadingConfig::default();
31
        let system_style = SystemStyle::detect();
31
        let mut s = Self {
31
            log_level,
31
            enable_visual_panic_hook: true,
31
            enable_logging_on_panic: true,
31
            termination_behavior: AppTerminationBehavior::default(),
31
            icon_provider,
31
            bundled_fonts,
31
            font_loading,
31
            mock_css_environment: OptionCssMockEnvironment::None,
31
            system_style,
31
            component_libraries: ComponentLibraryVec::from_const_slice(&[]),
31
            routes: RouteVec::from_const_slice(&[]),
31
            system_animations: SystemAnimations::default(),
31
            // ON by default: a precision touchpad is how most Windows laptops
31
            // pinch, and without this they cannot pinch at all.
31
            synthesize_pinch_from_ctrl_wheel: true,
31
            // OFF (user ruling): the app enables it or asks for the system's.
31
            natural_scroll: NaturalScroll::Disabled,
31
            // OFF: publishing a media player is visible in the desktop UI.
31
            expose_system_media_controls: false,
31
            custom_e2e_op: crate::events::CustomE2eOpCallback::default(),
31
            updates: UpdateSettings::default(),
31
            changelog_md: azul_css::OptionString::None,
31
            report_problem: OptionEmailAddress::None,
31
        };
        // Dogfood: register the 52 built-in HTML elements via the
        // same `add_component_library` API that users call.
        // Annotated binding coerces the fn item to the fn-pointer type that
        // `Into<RegisterComponentLibraryFn>` is implemented for (no `as` cast).
31
        let register_builtin: crate::xml::RegisterComponentLibraryFnType =
31
            crate::xml::register_builtin_components;
31
        s.add_component_library(AzString::from_const_str("builtin"), register_builtin);
31
        s
31
    }
    /// Create config with a mock CSS environment for testing
    ///
    /// This allows you to simulate how your app would look on a different OS,
    /// with a different theme, language, or accessibility settings.
    ///
    /// # Example
    /// ```rust
    /// # use azul_core::resources::{AppConfig, CssMockEnvironment};
    /// # use azul_css::dynamic_selector::{OsCondition, OptionOsCondition, ThemeCondition, OptionThemeCondition};
    /// let config = AppConfig::create()
    ///     .with_mock_environment(CssMockEnvironment {
    ///         os: OptionOsCondition::Some(OsCondition::Linux),
    ///         theme: OptionThemeCondition::Some(ThemeCondition::Dark),
    ///         ..Default::default()
    ///     });
    /// ```
    #[must_use]
3
    pub fn with_mock_environment(mut self, env: CssMockEnvironment) -> Self {
3
        self.mock_css_environment = OptionCssMockEnvironment::Some(env);
3
        self
3
    }
    /// Register a single component into a named library.
    ///
    /// Calls `register_fn` immediately and adds the returned `ComponentDef`
    /// to the library named `library`. If no library with that name exists,
    /// a new one is created. If a component with the same `id.name` already
    /// exists in the library, it is replaced.
    ///
    /// # C API
    /// ```c
    /// AzAppConfig_addComponent(&config, AzString_fromConstStr("mylib"), my_register_fn);
    /// ```
    pub fn add_component<R: Into<RegisterComponentFn>>(
        &mut self,
        library: AzString,
        register_fn: R,
    ) {
        let register_fn = register_fn.into();
        let component = (register_fn.cb)();
        let empty_libs = ComponentLibraryVec::from_const_slice(&[]);
        let mut libs =
            core::mem::replace(&mut self.component_libraries, empty_libs).into_library_owned_vec();
        if let Some(existing_lib) = libs
            .iter_mut()
            .find(|l| l.name.as_str() == library.as_str())
        {
            let empty_comps = ComponentDefVec::from_const_slice(&[]);
            let mut comps = core::mem::replace(&mut existing_lib.components, empty_comps)
                .into_library_owned_vec();
            if let Some(ec) = comps
                .iter_mut()
                .find(|c| c.id.name.as_str() == component.id.name.as_str())
            {
                *ec = component;
            } else {
                comps.push(component);
            }
            existing_lib.components = ComponentDefVec::from_vec(comps);
        } else {
            libs.push(ComponentLibrary {
                name: library,
                version: AzString::from_const_str("1.0.0"),
                description: AzString::from_const_str(""),
                components: ComponentDefVec::from_vec(alloc::vec![component]),
                exportable: true,
                modifiable: true,
                data_models: crate::xml::ComponentDataModelVec::from_const_slice(&[]),
                enum_models: crate::xml::ComponentEnumModelVec::from_const_slice(&[]),
            });
        }
        self.component_libraries = ComponentLibraryVec::from_vec(libs);
    }
    /// Register an entire component library.
    ///
    /// Calls `register_fn` immediately and adds the returned
    /// `ComponentLibrary` to the config. Uses `name` as the library name
    /// (overriding whatever the function sets). If a library with the same
    /// name already exists, it is replaced wholesale.
    ///
    /// # C API
    /// ```c
    /// AzAppConfig_addComponentLibrary(&config, AzString_fromConstStr("vendor"), my_lib_fn);
    /// ```
34
    pub fn add_component_library<R: Into<RegisterComponentLibraryFn>>(
34
        &mut self,
34
        name: AzString,
34
        register_fn: R,
34
    ) {
34
        let register_fn = register_fn.into();
34
        let mut library = (register_fn.cb)();
34
        library.name = name;
34
        let empty_libs = ComponentLibraryVec::from_const_slice(&[]);
34
        let mut libs =
34
            core::mem::replace(&mut self.component_libraries, empty_libs).into_library_owned_vec();
34
        if let Some(existing) = libs
34
            .iter_mut()
34
            .find(|l| l.name.as_str() == library.name.as_str())
1
        {
1
            *existing = library;
33
        } else {
33
            libs.push(library);
33
        }
34
        self.component_libraries = ComponentLibraryVec::from_vec(libs);
34
    }
    /// Register a route mapping a URL pattern to a layout callback.
    ///
    /// On web: each route becomes an HTTP endpoint. On desktop: the first
    /// route (or `"/"`) is the initial layout, and `CallbackInfo::switch_route()`
    /// swaps the active callback.
    ///
    /// # C API
    /// ```c
    /// AzAppConfig_addRoute(&config, AzString_fromConstStr("/user/:id"), layout_user);
    /// ```
6
    pub fn add_route<P: Into<AzString>, L: Into<LayoutCallback>>(
6
        &mut self,
6
        pattern: P,
6
        layout_fn: L,
6
    ) {
6
        let route = Route {
6
            pattern: pattern.into(),
6
            layout_callback: layout_fn.into(),
6
        };
6
        let empty = RouteVec::from_const_slice(&[]);
6
        let mut routes = core::mem::replace(&mut self.routes, empty).into_library_owned_vec();
        // Replace existing route with the same pattern
6
        if let Some(existing) = routes
6
            .iter_mut()
6
            .find(|r| r.pattern.as_str() == route.pattern.as_str())
1
        {
1
            *existing = route;
5
        } else {
5
            routes.push(route);
5
        }
6
        self.routes = RouteVec::from_vec(routes);
6
    }
    /// Find the route matching a given URL path.
    ///
    /// Returns the matched `Route` and a `RouteMatch` with extracted parameters.
    #[must_use]
9
    pub fn match_route_for_path(&self, path: &str) -> Option<(&Route, RouteMatch)> {
15
        for route in self.routes.as_ref() {
15
            if let Some(m) = match_route(route.pattern.as_str(), path) {
6
                return Some((route, m));
9
            }
        }
3
        None
9
    }
}
impl Default for AppConfig {
    fn default() -> Self {
        Self::create()
    }
}
/// How the engine treats scroll direction (9b-ii-b-i-a) - see
/// `AppConfig::natural_scroll`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(C)]
pub enum NaturalScroll {
    /// Never flip a delta in the engine. The OS's own preference, if the user
    /// set one, still reaches the app in the deltas.
    #[default]
    Disabled,
    /// Flip every wheel and trackpad delta in the engine.
    Enabled,
    /// Read the platform's preference at startup and keep it readable; no
    /// engine flip, since the platform already applied it to the deltas.
    System,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum AppLogLevel {
    Off,
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}
/// Metadata (but not storage) describing an image In `WebRender`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ImageDescriptor {
    /// Format of the image data.
    pub format: RawImageFormat,
    /// Width and height of the image data, in pixels.
    pub width: usize,
    pub height: usize,
    /// The number of bytes from the start of one row to the next. If non-None,
    /// `compute_stride` will return this value, otherwise it returns
    /// `width * bpp`. Different source of images have different alignment
    /// constraints for rows, so the stride isn't always equal to width * bpp.
    pub stride: OptionI32,
    /// Offset in bytes of the first pixel of this image in its backing buffer.
    /// This is used for tiling, wherein `WebRender` extracts chunks of input images
    /// in order to cache, manipulate, and render them individually. This offset
    /// tells the texture upload machinery where to find the bytes to upload for
    /// this tile. Non-tiled images generally set this to zero.
    pub offset: i32,
    /// Various bool flags related to this descriptor.
    pub flags: ImageDescriptorFlags,
}
/// Various flags that are part of an image descriptor.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ImageDescriptorFlags {
    /// Whether this image is opaque, or has an alpha channel. Avoiding blending
    /// for opaque surfaces is an important optimization.
    pub is_opaque: bool,
    /// Whether to allow the driver to automatically generate mipmaps. If images
    /// are already downscaled appropriately, mipmap generation can be wasted
    /// work, and cause performance problems on some cards/drivers.
    ///
    /// See <https://github.com/servo/webrender/pull/2555>/
    pub allow_mipmaps: bool,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IdNamespace(pub u32);
impl ::core::fmt::Display for IdNamespace {
9
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9
        write!(f, "IdNamespace({})", self.0)
9
    }
}
impl ::core::fmt::Debug for IdNamespace {
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1
        write!(f, "{self}")
1
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum RawImageFormat {
    R8,
    RG8,
    RGB8,
    RGBA8,
    R16,
    RG16,
    RGB16,
    RGBA16,
    BGR8,
    BGRA8,
    RGBF32,
    RGBAF32,
}
// NOTE: starts at 1 (0 = DUMMY)
static IMAGE_KEY: AtomicU64 = AtomicU64::new(1);
static FONT_KEY: AtomicU64 = AtomicU64::new(0);
static FONT_INSTANCE_KEY: AtomicU64 = AtomicU64::new(0);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ImageKey {
    pub namespace: IdNamespace,
    pub key: u64,
}
impl ImageKey {
    pub const DUMMY: Self = Self {
        namespace: IdNamespace(0),
        key: 0,
    };
3
    pub fn unique(render_api_namespace: IdNamespace) -> Self {
3
        Self {
3
            namespace: render_api_namespace,
3
            key: IMAGE_KEY.fetch_add(1, AtomicOrdering::SeqCst),
3
        }
3
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FontKey {
    pub namespace: IdNamespace,
    pub key: u64,
}
impl FontKey {
18
    pub fn unique(render_api_namespace: IdNamespace) -> Self {
18
        Self {
18
            namespace: render_api_namespace,
18
            key: FONT_KEY.fetch_add(1, AtomicOrdering::SeqCst),
18
        }
18
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FontInstanceKey {
    pub namespace: IdNamespace,
    pub key: u64,
}
impl FontInstanceKey {
6
    pub fn unique(render_api_namespace: IdNamespace) -> Self {
6
        Self {
6
            namespace: render_api_namespace,
6
            key: FONT_INSTANCE_KEY.fetch_add(1, AtomicOrdering::SeqCst),
6
        }
6
    }
}
// NOTE: This type should NOT be exposed in the API!
// The only public functions are the constructors
#[derive(Debug)]
pub enum DecodedImage {
    /// Image that has a reserved key, but no data, i.e it is not yet rendered
    /// or there was an error during rendering
    NullImage {
        width: usize,
        height: usize,
        format: RawImageFormat,
        /// Sometimes images need to be tagged with extra data
        tag: Vec<u8>,
    },
    // OpenGl texture
    Gl(Texture),
    // Image backed by CPU-rendered pixels
    Raw((ImageDescriptor, ImageData)),
    // Same as `Texture`, but rendered AFTER the layout has been done
    Callback(CoreImageCallback),
    // YUVImage(...)
    // VulkanSurface(...)
    // MetalSurface(...),
    // DirectXSurface(...)
}
#[derive(Debug)]
#[repr(C)]
pub struct ImageRef {
    /// Shared pointer to an opaque implementation of the decoded image
    pub data: *const DecodedImage,
    /// How many copies does this image have (if 0, the font data will be deleted on drop)
    pub copies: *const AtomicUsize,
    /// Process-unique, monotonically-assigned identity of the *decoded image*
    /// (see [`ImageRefHash`]). Shared by shallow clones (they are the same
    /// image), fresh for [`ImageRef::deep_copy`] and every `new_*` (a
    /// different image). Unlike the old `data`-pointer identity this is drawn
    /// from a never-reused counter, so freeing an image and reusing its heap
    /// address can never make a *new* image collide with a stale key — the
    /// prerequisite for image GC (see resources.rs `image_ref_get_hash`).
    pub id: u64,
    pub run_destructor: bool,
}
/// Never-reused source of [`ImageRef::id`]. Starts at 1 so `id == 0` can flag
/// an un-initialised / raw-reconstructed handle.
static IMAGE_REF_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
#[must_use]
5295
fn next_image_ref_id() -> u64 {
5295
    IMAGE_REF_ID_COUNTER.fetch_add(1, AtomicOrdering::SeqCst)
5295
}
impl ImageRef {
    #[must_use]
1367
    pub const fn get_hash(&self) -> ImageRefHash {
1367
        image_ref_get_hash(self)
1367
    }
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash, Ord, Eq)]
#[repr(C)]
pub struct ImageRefHash {
    pub inner: u64,
}
impl_option!(
    ImageRef,
    OptionImageRef,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl ImageRef {
    /// If *copies = 1, returns the internal image data
    #[must_use]
4
    pub fn into_inner(self) -> Option<DecodedImage> {
        // SAFETY: `data`/`copies` are non-null heap allocations from `Box::into_raw`
        // in `new()` (never mutated afterwards). When `copies == 1` we are the sole
        // owner, so reclaiming both Boxes and `forget`-ing `self` transfers ownership
        // without a double free / running the destructor twice.
        unsafe {
4
            if self.copies.as_ref().map(|m| m.load(AtomicOrdering::SeqCst)) == Some(1) {
2
                let data = Box::from_raw(self.data.cast_mut());
2
                drop(Box::from_raw(self.copies.cast_mut()));
2
                core::mem::forget(self); // do not run the destructor
2
                Some(*data)
            } else {
2
                None
            }
        }
4
    }
    #[must_use]
1460
    pub const fn get_data(&self) -> &DecodedImage {
        // SAFETY: `data` is a non-null, live `Box` allocation owned by this handle
        // (and its shallow clones) until the last copy drops; the returned borrow is
        // tied to `&self`, so it cannot outlive the allocation.
1460
        unsafe { &*self.data }
1460
    }
    #[must_use]
6
    pub fn get_image_callback(&self) -> Option<&CoreImageCallback> {
        // SAFETY: `copies` is a non-null, live allocation for the lifetime of `&self`.
6
        if unsafe { self.copies.as_ref().map(|m| m.load(AtomicOrdering::SeqCst)) != Some(1) } {
2
            return None; // not safe: shared, so no exclusive borrow of the data
4
        }
        // SAFETY: `data` is a non-null, live `Box` allocation; borrow tied to `&self`.
4
        match unsafe { &*self.data } {
2
            DecodedImage::Callback(gl_texture_callback) => Some(gl_texture_callback),
2
            _ => None,
        }
6
    }
2
    pub fn get_image_callback_mut(&mut self) -> Option<&mut CoreImageCallback> {
        // SAFETY: `copies` is a non-null, live allocation for the lifetime of `&self`.
2
        if unsafe { self.copies.as_ref().map(|m| m.load(AtomicOrdering::SeqCst)) != Some(1) } {
1
            return None; // not safe: shared, so a &mut would alias other clones' data
1
        }
        // SAFETY: `copies == 1` proven above, so `&mut self` is the unique owner of
        // the `data` allocation; the exclusive borrow is tied to `&mut self`.
1
        match unsafe { &mut *self.data.cast_mut() } {
1
            DecodedImage::Callback(gl_texture_callback) => Some(gl_texture_callback),
            _ => None,
        }
2
    }
    /// In difference to the default shallow copy, creates a new image ref
    #[must_use]
3
    pub fn deep_copy(&self) -> Self {
3
        let new_data = match self.get_data() {
            DecodedImage::NullImage {
2
                width,
2
                height,
2
                format,
2
                tag,
2
            } => DecodedImage::NullImage {
2
                width: *width,
2
                height: *height,
2
                format: *format,
2
                tag: tag.clone(),
2
            },
            // NOTE: textures cannot be deep-copied yet (since the OpenGL calls for that
            // are missing from the trait), so calling clone() on a GL texture will result in an
            // empty image
            DecodedImage::Gl(tex) => DecodedImage::NullImage {
                width: tex.size.width as usize,
                height: tex.size.height as usize,
                format: tex.format,
                tag: Vec::new(),
            },
            // WARNING: the data may still be a U8Vec<'static> - the data may still not be
            // actually cloned. The data only gets cloned on a write operation
            DecodedImage::Raw((descriptor, data)) => DecodedImage::Raw((*descriptor, data.clone())),
1
            DecodedImage::Callback(cb) => DecodedImage::Callback(cb.clone()),
        };
3
        Self::new(new_data)
3
    }
    #[must_use]
15
    pub const fn is_null_image(&self) -> bool {
15
        matches!(self.get_data(), DecodedImage::NullImage { .. })
15
    }
    #[must_use]
2
    pub const fn is_gl_texture(&self) -> bool {
2
        matches!(self.get_data(), DecodedImage::Gl(_))
2
    }
    #[must_use]
3
    pub const fn is_raw_image(&self) -> bool {
3
        matches!(self.get_data(), DecodedImage::Raw((_, _)))
3
    }
    #[must_use]
185
    pub const fn is_callback(&self) -> bool {
185
        matches!(self.get_data(), DecodedImage::Callback(_))
185
    }
    // OptionRawImage
    #[must_use]
3
    pub fn get_rawimage(&self) -> Option<RawImage> {
3
        match self.get_data() {
1
            DecodedImage::Raw((image_descriptor, image_data)) => Some(RawImage {
1
                pixels: match image_data {
1
                    ImageData::Raw(shared_data) => {
                        // Clone the SharedRawImageData (increments ref count),
                        // then try to extract or convert to U8Vec
1
                        let data_clone = shared_data.clone();
1
                        data_clone.into_inner().map_or_else(
1
                            || RawImageData::U8(shared_data.as_ref().to_vec().into()),
                            RawImageData::U8,
                        )
                    }
                    ImageData::External(_) => return None,
                },
1
                width: image_descriptor.width,
1
                height: image_descriptor.height,
                premultiplied_alpha: true,
1
                data_format: image_descriptor.format,
1
                tag: Vec::new().into(),
            }),
2
            _ => None,
        }
3
    }
    /// Get raw bytes from the image as a slice
    /// Returns None if this is not a Raw image or if it's an External image
    #[must_use]
3
    pub fn get_bytes(&self) -> Option<&[u8]> {
3
        match self.get_data() {
1
            DecodedImage::Raw((_, image_data)) => match image_data {
1
                ImageData::Raw(shared_data) => Some(shared_data.as_ref()),
                ImageData::External(_) => None,
            },
2
            _ => None,
        }
3
    }
    /// Get a pointer to the raw bytes for debugging/profiling purposes
    /// Returns a unique pointer for this `ImageRef`'s data
    #[must_use]
3
    pub fn get_bytes_ptr(&self) -> *const u8 {
3
        match self.get_data() {
1
            DecodedImage::Raw((_, image_data)) => match image_data {
1
                ImageData::Raw(shared_data) => shared_data.as_ptr(),
                ImageData::External(_) => core::ptr::null(),
            },
2
            _ => core::ptr::null(),
        }
3
    }
    /// NOTE: returns (0, 0) for a Callback
    #[allow(clippy::cast_precision_loss)] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[must_use]
486
    pub const fn get_size(&self) -> LogicalSize {
486
        match self.get_data() {
414
            DecodedImage::NullImage { width, height, .. } => {
414
                LogicalSize::new(*width as f32, *height as f32)
            }
            DecodedImage::Gl(tex) => {
                LogicalSize::new(tex.size.width as f32, tex.size.height as f32)
            }
71
            DecodedImage::Raw((image_descriptor, _)) => LogicalSize::new(
71
                image_descriptor.width as f32,
71
                image_descriptor.height as f32,
            ),
1
            DecodedImage::Callback(_) => LogicalSize::new(0.0, 0.0),
        }
486
    }
    #[must_use]
3957
    pub fn null_image(width: usize, height: usize, format: RawImageFormat, tag: Vec<u8>) -> Self {
3957
        Self::new(DecodedImage::NullImage {
3957
            width,
3957
            height,
3957
            format,
3957
            tag,
3957
        })
3957
    }
18
    pub fn callback<C: Into<CoreRenderImageCallback>>(callback: C, data: RefAny) -> Self {
18
        Self::new(DecodedImage::Callback(CoreImageCallback {
18
            callback: callback.into(),
18
            refany: data,
18
        }))
18
    }
    #[must_use]
1381
    pub fn new_rawimage(image_data: RawImage) -> Option<Self> {
1381
        let (image_data, image_descriptor) = image_data.into_loaded_image_source()?;
1150
        Some(Self::new(DecodedImage::Raw((image_descriptor, image_data))))
1381
    }
    #[must_use]
    pub fn new_gltexture(texture: Texture) -> Self {
        Self::new(DecodedImage::Gl(texture))
    }
5293
    fn new(data: DecodedImage) -> Self {
5293
        Self {
5293
            data: Box::into_raw(Box::new(data)),
5293
            copies: Box::into_raw(Box::new(AtomicUsize::new(1))),
5293
            id: next_image_ref_id(),
5293
            run_destructor: true,
5293
        }
5293
    }
    // pub fn new_vulkan(...) -> Self
}
// SAFETY: the raw pointers only ever address heap `Box`es whose contents are
// themselves `Send`/`Sync`, and all cross-thread refcount mutation goes through the
// `AtomicUsize` in `copies`, so sharing/moving a handle across threads is sound.
unsafe impl Send for ImageRef {}
unsafe impl Sync for ImageRef {}
// Identity is the never-reused `id`, NOT the `data` pointer: two shallow
// clones of one image share an `id` (equal); distinct images (incl. a
// `deep_copy`) get distinct ids; a freed image's id is never handed to a
// later image, so a reused heap address can't forge equality.
impl PartialEq for ImageRef {
56
    fn eq(&self, rhs: &Self) -> bool {
56
        self.id == rhs.id
56
    }
}
impl PartialOrd for ImageRef {
    fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
        Some(self.id.cmp(&other.id))
    }
}
impl Ord for ImageRef {
1
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1
        self.id.cmp(&other.id)
1
    }
}
impl Eq for ImageRef {}
impl Hash for ImageRef {
395
    fn hash<H>(&self, state: &mut H)
395
    where
395
        H: Hasher,
    {
395
        self.id.hash(state);
395
    }
}
impl Clone for ImageRef {
1462
    fn clone(&self) -> Self {
        // SAFETY: `copies` is a non-null, live `AtomicUsize` allocation shared by all
        // clones; the atomic increment balances the `fetch_sub` in `Drop`.
        unsafe {
1462
            self.copies
1462
                .as_ref()
1462
                .map(|m| m.fetch_add(1, AtomicOrdering::SeqCst));
        }
1462
        Self {
1462
            data: self.data,     // copy the pointer
1462
            copies: self.copies, // copy the pointer
1462
            id: self.id,         // same image → same identity
1462
            run_destructor: true,
1462
        }
1462
    }
}
impl Drop for ImageRef {
6753
    fn drop(&mut self) {
6753
        self.run_destructor = false;
        // SAFETY: `data`/`copies` are non-null, live `Box` allocations shared by all
        // clones. `fetch_sub` returns the pre-decrement count, so `== 1` means this is
        // the last owner; only then do we reclaim both Boxes exactly once.
        unsafe {
6753
            let copies = (*self.copies).fetch_sub(1, AtomicOrdering::SeqCst);
6753
            if copies == 1 {
5291
                drop(Box::from_raw(self.data.cast_mut()));
5291
                drop(Box::from_raw(self.copies.cast_mut()));
5303
            }
        }
6753
    }
}
#[must_use]
1496
pub const fn image_ref_get_hash(ir: &ImageRef) -> ImageRefHash {
    // The identity is the never-reused `id`, not the freeable `data` pointer
    // (see the `id` field docs). This is what makes an ImageKey safe to
    // DeleteImage: once an image is dropped its id is retired forever, so a
    // future image that reuses the same heap address gets a *different* key
    // and is registered/uploaded correctly instead of aliasing the stale one.
1496
    ImageRefHash { inner: ir.id }
1496
}
/// Convert a stable `ImageRefHash` directly to an `ImageKey`.
///
/// `ImageKey.key` is a `u64` and `ImageRefHash.inner` is the `ImageRef` `id`
/// (a `u64` counter) stored in a `usize`; on a 32-bit host that truncates the
/// top 32 bits, which is fine — a run would need 4 billion live images for the
/// low 32 bits to collide.
#[must_use]
7
pub const fn image_ref_hash_to_image_key(hash: ImageRefHash, namespace: IdNamespace) -> ImageKey {
7
    ImageKey {
7
        namespace,
7
        key: hash.inner,
7
    }
7
}
#[must_use]
6
pub fn font_ref_get_hash(fr: &FontRef) -> u64 {
6
    fr.get_hash()
6
}
/// Stores the resources for the application, such as fonts, images and cached
/// texts, also clipboard strings
///
/// Images and fonts can be references across window contexts (not yet tested,
/// but should work).
#[derive(Debug, Default)]
pub struct ImageCache {
    /// The `AzString` is the string used in the CSS, i.e. `url("my_image`") = "`my_image`" ->
    /// ImageId(4)
    ///
    /// NOTE: This is the only map that is modifiable by the user and that has to be manually
    /// managed all other maps are library-internal only and automatically delete their
    /// resources once they aren't needed anymore
    pub image_id_map: OrderedMap<AzString, ImageRef>,
}
impl ImageCache {
    #[must_use]
3
    pub fn new() -> Self {
3
        Self::default()
3
    }
    // -- ImageId cache
7
    pub fn add_css_image_id(&mut self, css_id: AzString, image: ImageRef) {
7
        self.image_id_map.insert(css_id, image);
7
    }
    #[must_use]
25
    pub fn get_css_image_id(&self, css_id: &AzString) -> Option<&ImageRef> {
25
        self.image_id_map.get(css_id)
25
    }
4
    pub fn delete_css_image_id(&mut self, css_id: &AzString) {
4
        self.image_id_map.remove(css_id);
4
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ResolvedImage {
    pub key: ImageKey,
    pub descriptor: ImageDescriptor,
}
/// Trait for accessing font resources
pub trait RendererResourcesTrait: fmt::Debug {
    /// Get a font family hash from a font families hash
    fn get_font_family(
        &self,
        style_font_families_hash: &StyleFontFamiliesHash,
    ) -> Option<&StyleFontFamilyHash>;
    /// Get a font key from a font family hash
    fn get_font_key(&self, style_font_family_hash: &StyleFontFamilyHash) -> Option<&FontKey>;
    /// Get a registered font and its instances from a font key
    fn get_registered_font(
        &self,
        font_key: &FontKey,
    ) -> Option<&(FontRef, OrderedMap<(Au, DpiScaleFactor), FontInstanceKey>)>;
    /// Get image information from an image hash
    fn get_image(&self, hash: &ImageRefHash) -> Option<&ResolvedImage>;
    /// Update an image descriptor for an existing image hash
    fn update_image(&mut self, image_ref_hash: &ImageRefHash, descriptor: ImageDescriptor);
}
// Implementation for the original RendererResources struct
impl RendererResourcesTrait for RendererResources {
43
    fn get_font_family(
43
        &self,
43
        style_font_families_hash: &StyleFontFamiliesHash,
43
    ) -> Option<&StyleFontFamilyHash> {
43
        self.font_families_map.get(style_font_families_hash)
43
    }
6
    fn get_font_key(&self, style_font_family_hash: &StyleFontFamilyHash) -> Option<&FontKey> {
6
        self.font_id_map.get(style_font_family_hash)
6
    }
5
    fn get_registered_font(
5
        &self,
5
        font_key: &FontKey,
5
    ) -> Option<&(FontRef, OrderedMap<(Au, DpiScaleFactor), FontInstanceKey>)> {
5
        self.currently_registered_fonts.get(font_key)
5
    }
4
    fn get_image(&self, hash: &ImageRefHash) -> Option<&ResolvedImage> {
4
        self.currently_registered_images.get(hash)
4
    }
2
    fn update_image(&mut self, image_ref_hash: &ImageRefHash, descriptor: ImageDescriptor) {
2
        if let Some(s) = self.currently_registered_images.get_mut(image_ref_hash) {
1
            s.descriptor = descriptor;
1
        }
2
    }
}
/// Renderer resources that manage font, image and font instance keys.
/// `RendererResources` are local to each renderer / window, since the
/// keys are not shared across renderers
///
/// The resources are automatically managed, meaning that they each new frame
/// (signified by `start_frame_gc` and `end_frame_gc`)
#[derive(Default)]
pub struct RendererResources {
    /// All image keys currently active in the `RenderApi`
    pub currently_registered_images: OrderedMap<ImageRefHash, ResolvedImage>,
    /// Reverse lookup: `ImageKey` -> `ImageRefHash` for display list translation
    pub image_key_map: OrderedMap<ImageKey, ImageRefHash>,
    /// Image GC bookkeeping: last epoch (as `u32`) each registered image was
    /// seen referenced by a display list. An image absent for more than
    /// `IMAGE_GC_KEEP_EPOCHS` frames is `DeleteImage`d and evicted — this is
    /// what stops the unbounded texture growth of a window that swaps images
    /// every frame (video / capture / animated charts). Safe because
    /// `ImageRefHash` is now a never-reused id, not a freeable pointer.
    pub image_last_seen_epoch: OrderedMap<ImageRefHash, u32>,
    /// All font keys currently active in the `RenderApi`
    pub currently_registered_fonts:
        OrderedMap<FontKey, (FontRef, OrderedMap<(Au, DpiScaleFactor), FontInstanceKey>)>,
    /// Fonts registered on the last frame
    ///
    /// Fonts differ from images in that regard that we can't immediately
    /// delete them on a new frame, instead we have to delete them on "current frame + 1"
    /// This is because when the frame is being built, we do not know
    /// whether the font will actually be successfully loaded
    pub last_frame_registered_fonts:
        OrderedMap<FontKey, OrderedMap<(Au, DpiScaleFactor), FontInstanceKey>>,
    /// Map from the calculated families vec (`["Arial", "Helvetica"]`)
    /// to the final loaded font that could be loaded
    /// (in this case "Arial" on Windows and "Helvetica" on Mac,
    /// because the fonts are loaded in fallback-order)
    pub font_families_map: OrderedMap<StyleFontFamiliesHash, StyleFontFamilyHash>,
    /// Same as `AzString` -> `ImageId`, but for fonts, i.e. "Roboto" -> FontId(9)
    pub font_id_map: OrderedMap<StyleFontFamilyHash, FontKey>,
    /// Direct mapping from font hash (from `FontRef`) to `FontKey`
    /// TODO: This should become part of `SharedFontRegistry`
    pub font_hash_map: OrderedMap<u64, FontKey>,
}
impl fmt::Debug for RendererResources {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "RendererResources {{
                currently_registered_images: {:#?},
                currently_registered_fonts: {:#?},
                font_families_map: {:#?},
                font_id_map: {:#?},
            }}",
            self.currently_registered_images.keys().collect::<Vec<_>>(),
            self.currently_registered_fonts.keys().collect::<Vec<_>>(),
            self.font_families_map.keys().collect::<Vec<_>>(),
            self.font_id_map.keys().collect::<Vec<_>>(),
        )
    }
}
impl RendererResources {
    #[must_use]
2
    pub fn get_renderable_font_data(
2
        &self,
2
        font_instance_key: &FontInstanceKey,
2
    ) -> Option<(&FontRef, Au, DpiScaleFactor)> {
2
        self.currently_registered_fonts
2
            .iter()
2
            .find_map(|(font_key, (font_ref, instances))| {
1
                instances.iter().find_map(|((au, dpi), instance_key)| {
1
                    if *instance_key == *font_instance_key {
1
                        Some((font_ref, *au, *dpi))
                    } else {
                        None
                    }
1
                })
1
            })
2
    }
    #[allow(clippy::cast_possible_truncation)] // image/graphics: bounded
                                               // pixel/colour/dimension/unit casts
36
    pub fn get_font_instance_key_for_text(
36
        &self,
36
        font_size_px: f32,
36
        css_property_cache: &CssPropertyCache,
36
        node_data: &NodeData,
36
        node_id: &NodeId,
36
        styled_node_state: &StyledNodeState,
36
        dpi_scale: f32,
36
    ) -> Option<FontInstanceKey> {
        // Convert font size to StyleFontSize.
        //
        // `font_size_px as isize` saturates +inf / f32::MAX to isize::MAX (and
        // -inf / -f32::MAX to isize::MIN). `const_px` then multiplies by 1000
        // (FP_PRECISION_MULTIPLIER) inside `FloatValue::const_new`, which would
        // overflow. Clamp to the range that survives that multiply so an absurd
        // size misses cleanly instead of panicking.
36
        let font_size_isize = (font_size_px as isize).clamp(isize::MIN / 1000, isize::MAX / 1000);
36
        let font_size = StyleFontSize {
36
            inner: azul_css::props::basic::PixelValue::const_px(font_size_isize),
36
        };
        // Convert to application units
36
        let font_size_au = font_size_to_au(font_size);
        // Create DPI scale factor
36
        let dpi_scale_factor = DpiScaleFactor {
36
            inner: FloatValue::new(dpi_scale),
36
        };
        // Get font family
36
        let font_family =
36
            css_property_cache.get_font_id_or_default(node_data, node_id, styled_node_state);
        // Calculate hash and lookup font instance key
36
        let font_families_hash = StyleFontFamiliesHash::new(font_family.as_ref());
36
        self.get_font_instance_key(&font_families_hash, font_size_au, dpi_scale_factor)
36
    }
    #[must_use]
43
    pub fn get_font_instance_key(
43
        &self,
43
        font_families_hash: &StyleFontFamiliesHash,
43
        font_size_au: Au,
43
        dpi_scale: DpiScaleFactor,
43
    ) -> Option<FontInstanceKey> {
43
        let font_family_hash = self.get_font_family(font_families_hash)?;
5
        let font_key = self.get_font_key(font_family_hash)?;
5
        let (_, instances) = self.get_registered_font(font_key)?;
5
        instances.get(&(font_size_au, dpi_scale)).copied()
43
    }
    // Delete all font family hashes that do not have a font key anymore
    //
    // AUDIT-TODO (font GC, resources.rs font leak — 2026-07-08):
    // Fonts and font instances are currently NEVER garbage-collected. This helper
    // only prunes `font_id_map` / `font_families_map` entries whose `FontKey` has
    // *already* vanished from `currently_registered_fonts` — but nothing ever
    // removes fonts from `currently_registered_fonts` in the first place, and this
    // helper itself has no callers. No `DeleteFont` / `DeleteFontInstance`
    // `ResourceUpdate` is ever emitted, so WebRender font memory grows unbounded
    // when an app cycles fonts (font pickers, editors, live CSS).
    //
    // To wire a real font GC mirroring the image GC (see `dll/.../wr_translate2.rs`
    // `garbage_collect_images` + `image_last_seen_epoch`), the following are needed
    // and MUST be done together (do not half-implement):
    //   1. Add `font_last_seen_epoch: OrderedMap<FontKey, u32>` (and, if instance- level GC is
    //      wanted, per-`FontInstanceKey` epochs) to `RendererResources`.
    //   2. In the display-list build (dll crate), after resolving each glyph run's
    //      `FontInstanceKey`, mark the owning `FontKey` (and instance) seen at the current epoch —
    //      exactly as images are marked in the image GC.
    //   3. Add a `garbage_collect_fonts(&mut self, now, keep_epochs, updates)` that, for every
    //      `FontKey` unseen for > keep_epochs frames, emits `DeleteFontInstance` for each of its
    //      instances then `DeleteFont`, and evicts the key from `currently_registered_fonts`,
    //      `font_hash_map`, `last_frame_registered_fonts`, and `font_id_map`/`font_families_map`
    //      (via this helper). Respect the "delete on current frame + 1" rule already documented on
    //      `last_frame_registered_fonts`.
    //   4. Call it once per frame from the same site as the image GC.
    // Left as a TODO because steps 2 and 4 are cross-crate (dll) and cannot be
    // implemented from `azul-core` alone; adding a GC method here without a caller
    // would just be more dead code.
    #[allow(dead_code)]
2
    fn remove_font_families_with_zero_references(&mut self) {
2
        let font_family_to_delete = self
2
            .font_id_map
2
            .iter()
2
            .filter_map(|(font_family, font_key)| {
1
                if self.currently_registered_fonts.contains_key(font_key) {
                    None
                } else {
1
                    Some(*font_family)
                }
1
            })
2
            .collect::<Vec<_>>();
3
        for f in font_family_to_delete {
1
            self.font_id_map.remove(&f); // font key does not exist anymore
1
        }
2
        let font_families_to_delete = self
2
            .font_families_map
2
            .iter()
2
            .filter_map(|(font_families, font_family)| {
1
                if self.font_id_map.contains_key(font_family) {
                    None
                } else {
1
                    Some(*font_families)
                }
1
            })
2
            .collect::<Vec<_>>();
3
        for f in font_families_to_delete {
1
            self.font_families_map.remove(&f); // font family does not exist anymore
1
        }
2
    }
}
// Result returned from rerender_image_callback() - should be used as:
//
// ```rust
// txn.update_image(
//     wr_translate_image_key(key),
//     wr_translate_image_descriptor(descriptor),
//     wr_translate_image_data(data),
//     &WrImageDirtyRect::All,
// );
// ```
#[derive(Debug, Clone)]
pub struct UpdateImageResult {
    pub key_to_update: ImageKey,
    pub new_descriptor: ImageDescriptor,
    pub new_image_data: ImageData,
}
#[derive(Debug, Default)]
pub struct GlTextureCache {
    pub solved_textures:
        BTreeMap<DomId, BTreeMap<NodeId, (ImageKey, ImageDescriptor, ExternalImageId)>>,
    pub hashes: BTreeMap<(DomId, NodeId, ImageRefHash), ImageRefHash>,
}
// necessary so the display list can be built in parallel
// SAFETY: only the raw pointers inside the contained `ImageRefHash`/key maps are
// non-`Send`-inferring; every stored value is a plain POD id/descriptor with no
// interior aliasing, so moving the cache to another thread is sound.
unsafe impl Send for GlTextureCache {}
impl GlTextureCache {
    /// Initializes an empty cache
    #[must_use]
1
    pub const fn empty() -> Self {
1
        Self {
1
            solved_textures: BTreeMap::new(),
1
            hashes: BTreeMap::new(),
1
        }
1
    }
    /// Updates a given texture
    ///
    /// This is called when a texture needs to be re-rendered (e.g., on resize or animation frame).
    /// It updates the texture in the `WebRender` external image cache and updates the internal
    /// descriptor to reflect the new size.
    ///
    /// # Arguments
    ///
    /// * `dom_id` - The DOM ID containing the texture
    /// * `node_id` - The node ID of the image element
    /// * `document_id` - The `WebRender` document ID
    /// * `epoch` - The current frame epoch
    /// * `new_texture` - The new texture to use
    /// * `insert_into_active_gl_textures_fn` - Function to insert the texture into the cache
    ///
    /// # Returns
    ///
    /// The `ExternalImageId` if successful, None if the texture wasn't found in the cache
    pub fn update_texture(
        &mut self,
        dom_id: DomId,
        node_id: NodeId,
        document_id: DocumentId,
        epoch: Epoch,
        new_texture: Texture,
        insert_into_active_gl_textures_fn: &GlStoreImageFn,
    ) -> Option<ExternalImageId> {
        let new_descriptor = new_texture.get_descriptor();
        let di_map = self.solved_textures.get_mut(&dom_id)?;
        let entry = di_map.get_mut(&node_id)?;
        // Update the descriptor
        entry.1 = new_descriptor;
        // The ExternalImageId is deterministic from (dom_id, node_id), so the cache
        // entry can keep referencing the same id across re-renders.
        let external_image_id = texture_external_image_id(dom_id, node_id);
        (insert_into_active_gl_textures_fn)(document_id, epoch, new_texture, external_image_id);
        entry.2 = external_image_id;
        Some(external_image_id)
    }
}
macro_rules! unique_id {
    ($struct_name:ident, $counter_name:ident) => {
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
        #[repr(C)]
        pub struct $struct_name {
            pub id: usize,
        }
        impl $struct_name {
35286
            pub fn unique() -> Self {
35286
                Self {
35286
                    id: $counter_name.fetch_add(1, AtomicOrdering::SeqCst),
35286
                }
35286
            }
        }
    };
}
// NOTE: the property key is unique across transform, color and opacity properties
static PROPERTY_KEY_COUNTER: AtomicUsize = AtomicUsize::new(0);
unique_id!(TransformKey, PROPERTY_KEY_COUNTER);
unique_id!(ColorKey, PROPERTY_KEY_COUNTER);
unique_id!(OpacityKey, PROPERTY_KEY_COUNTER);
static IMAGE_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
unique_id!(ImageId, IMAGE_ID_COUNTER);
static FONT_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
unique_id!(FontId, FONT_ID_COUNTER);
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub struct ImageMask {
    pub image: ImageRef,
    pub rect: LogicalRect,
    pub repeat: bool,
}
impl_option!(
    ImageMask,
    OptionImageMask,
    copy = false,
    [Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash]
);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImmediateFontId {
    Resolved((StyleFontFamilyHash, FontKey)),
    Unresolved(StyleFontFamilyVec),
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[repr(C, u8)]
pub enum RawImageData {
    // 8-bit image data
    U8(U8Vec),
    // 16-bit image data
    U16(U16Vec),
    // HDR image data
    F32(F32Vec),
}
impl RawImageData {
    #[must_use]
41
    pub const fn get_u8_vec_ref(&self) -> Option<&U8Vec> {
41
        match self {
39
            Self::U8(v) => Some(v),
2
            _ => None,
        }
41
    }
    #[must_use]
3
    pub const fn get_u16_vec_ref(&self) -> Option<&U16Vec> {
3
        match self {
1
            Self::U16(v) => Some(v),
2
            _ => None,
        }
3
    }
    #[must_use]
12
    pub const fn get_f32_vec_ref(&self) -> Option<&F32Vec> {
12
        match self {
8
            Self::F32(v) => Some(v),
4
            _ => None,
        }
12
    }
1395
    fn get_u8_vec(self) -> Option<U8Vec> {
1395
        match self {
1387
            Self::U8(v) => Some(v),
8
            _ => None,
        }
1395
    }
18
    fn get_u16_vec(self) -> Option<U16Vec> {
18
        match self {
13
            Self::U16(v) => Some(v),
5
            _ => None,
        }
18
    }
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct RawImage {
    pub pixels: RawImageData,
    pub width: usize,
    pub height: usize,
    pub premultiplied_alpha: bool,
    pub data_format: RawImageFormat,
    pub tag: U8Vec,
}
/// A soft round brush for the painting API.
///
/// The same parameters drive the CPU
/// rasterizer ([`RawImage::paint_dot`]) and the GPU brush shader, so a stroke
/// looks identical whether it lands on a `RawImage` or a `Texture`.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Brush {
    /// Brush color (its alpha scales the dab opacity together with `flow`).
    pub color: ColorU,
    /// Brush radius in pixels.
    pub radius: f32,
    /// Edge hardness, `0.0` (fully feathered) .. `1.0` (hard edge). Opaque out
    /// to `hardness * radius`, then a smooth falloff to zero at the edge.
    pub hardness: f32,
    /// Per-dab opacity multiplier, `0.0`..`1.0`. Values < 1 let overlapping dabs
    /// build up smoothly (the "metaball"-like blend).
    pub flow: f32,
    /// Spacing between stamped dabs along a stroke, as a fraction of `radius`
    /// (e.g. `0.25` = a dab every quarter-radius). Smaller = smoother + slower.
    pub spacing: f32,
}
impl Brush {
    /// A sensible default brush: medium-soft, full flow, dense spacing.
    #[must_use]
45
    pub const fn new(color: ColorU, radius: f32) -> Self {
45
        Self {
45
            color,
45
            radius,
45
            hardness: 0.5,
45
            flow: 1.0,
45
            spacing: 0.25,
45
        }
45
    }
}
/// Brush dab coverage: `1.0` at the dab center, smoothly `0.0` at its edge.
///
/// `t` is `distance / radius` in `[0, 1]`; `hardness` in `[0, 1]`. Single source
/// of truth for the dab profile -- the GPU brush shader computes the identical
/// `1 - smoothstep(hardness, 1, t)` so CPU and GPU strokes match.
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
#[inline]
#[must_use]
1600
pub fn brush_dab_coverage(t: f32, hardness: f32) -> f32 {
1600
    let edge0 = hardness.clamp(0.0, 1.0);
1600
    let denom = (1.0 - edge0).max(1.0e-4);
1600
    let x = ((t - edge0) / denom).clamp(0.0, 1.0);
1600
    1.0 - (x * x * (3.0 - 2.0 * x))
1600
}
impl RawImage {
    /// CPU painting: stamp one brush dab centered at (`cx`, `cy`) in pixel
    /// coordinates, alpha-over compositing a radial-falloff disc. Only 8-bit
    /// `RGBA8`/`BGRA8` images are painted (other formats are left untouched).
    /// This is the CPU mirror of the GPU brush shader.
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_precision_loss,
        clippy::cast_sign_loss
    )] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[allow(clippy::cast_possible_wrap)] // image/graphics: bounded pixel/colour casts
160
    pub fn paint_dot(&mut self, cx: f32, cy: f32, brush: Brush) {
160
        let r = brush.radius;
        // `!(r > 0.0)` intentionally also rejects NaN (`r <= 0.0` would not).
        #[allow(clippy::neg_cmp_op_on_partial_ord)]
160
        if !(r > 0.0) || self.width == 0 || self.height == 0 {
15
            return;
145
        }
145
        let bgr = match self.data_format {
140
            RawImageFormat::RGBA8 => false,
1
            RawImageFormat::BGRA8 => true,
4
            _ => return,
        };
141
        let (w, h) = (self.width as i32, self.height as i32);
141
        let buf: &mut [u8] = match self.pixels {
141
            RawImageData::U8(ref mut v) => v.as_mut(),
            _ => return,
        };
141
        let flow = brush.flow.clamp(0.0, 1.0) * (f32::from(brush.color.a) / 255.0);
141
        let (cr, cg, cb) = (
141
            f32::from(brush.color.r),
141
            f32::from(brush.color.g),
141
            f32::from(brush.color.b),
141
        );
141
        let x0 = (cx - r).floor().max(0.0) as i32;
141
        let y0 = (cy - r).floor().max(0.0) as i32;
141
        let x1 = ((cx + r).ceil() as i32).min(w);
141
        let y1 = ((cy + r).ceil() as i32).min(h);
564
        for y in y0..y1 {
2360
            for x in x0..x1 {
2360
                let dx = x as f32 + 0.5 - cx;
2360
                let dy = y as f32 + 0.5 - cy;
2360
                let dist = dx.hypot(dy);
2360
                if dist > r {
881
                    continue;
1479
                }
1479
                let a = brush_dab_coverage(dist / r, brush.hardness) * flow;
1479
                if a <= 0.0 {
36
                    continue;
1443
                }
1443
                let idx = ((y * w + x) as usize) * 4;
                // `width`/`height` are public and may exceed the actual buffer;
                // trust the buffer, not the claimed dimensions, so a mismatch
                // skips the pixel instead of indexing out of bounds.
1443
                if idx + 4 > buf.len() {
52
                    continue;
1391
                }
1391
                let (ri, gi, bi, ai) = if bgr {
12
                    (idx + 2, idx + 1, idx, idx + 3)
                } else {
1379
                    (idx, idx + 1, idx + 2, idx + 3)
                };
1391
                let inv = 1.0 - a;
1391
                buf[ri] = (cr * a + f32::from(buf[ri]) * inv)
1391
                    .round()
1391
                    .clamp(0.0, 255.0) as u8;
1391
                buf[gi] = (cg * a + f32::from(buf[gi]) * inv)
1391
                    .round()
1391
                    .clamp(0.0, 255.0) as u8;
1391
                buf[bi] = (cb * a + f32::from(buf[bi]) * inv)
1391
                    .round()
1391
                    .clamp(0.0, 255.0) as u8;
1391
                buf[ai] = ((a + (f32::from(buf[ai]) / 255.0) * inv) * 255.0)
1391
                    .round()
1391
                    .clamp(0.0, 255.0) as u8;
            }
        }
160
    }
    /// CPU painting: stamp a stroke by spacing dabs along the segment
    /// (`x0`,`y0`)->(`x1`,`y1`). Call once per pointer move with the previous and
    /// current positions for a continuous line.
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // image/graphics:
                                                                            // bounded pixel/colour/
                                                                            // dimension/unit casts
8
    pub fn paint_stroke(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, brush: Brush) {
8
        let dx = x1 - x0;
8
        let dy = y1 - y0;
8
        let len = dx.hypot(dy);
        // A non-finite length (infinite / NaN endpoint) would make `n` saturate
        // to i32::MAX and the `for i in 0..=n` loop run ~2.1 billion times. Bail
        // rather than spin: an infinite segment has no finite dabs to stamp.
8
        if !len.is_finite() {
2
            return;
6
        }
6
        let step = (brush.radius * brush.spacing.max(0.01)).max(0.5);
6
        let n = (len / step).floor() as i32;
6
        if n <= 0 {
1
            self.paint_dot(x1, y1, brush);
1
            return;
5
        }
84
        for i in 0..=n {
84
            let t = i as f32 / n as f32;
84
            self.paint_dot(x0 + dx * t, y0 + dy * t, brush);
84
        }
8
    }
}
/// Multiplies the RGB channels of a single 4-byte BGRA/RGBA pixel by its alpha.
///
/// From webrender/wrench. These are slow. Gecko's gfx/2d/Swizzle.cpp has better
/// versions.
#[inline]
#[allow(clippy::cast_possible_truncation)] // image/graphics: bounded pixel/colour/dimension/unit
                                           // casts
50709263
fn premultiply_alpha(array: &mut [u8]) {
50709263
    if array.len() != 4 {
6
        return;
50709257
    }
50709257
    let a = u32::from(array[3]);
50709257
    array[0] = (((u32::from(array[0]) * a) + 128) / 255) as u8;
50709257
    array[1] = (((u32::from(array[1]) * a) + 128) / 255) as u8;
50709257
    array[2] = (((u32::from(array[2]) * a) + 128) / 255) as u8;
50709263
}
#[inline]
#[allow(clippy::cast_possible_truncation)] // image/graphics: bounded pixel/colour/dimension/unit casts
#[allow(clippy::cast_sign_loss)] // image/graphics: bounded pixel/colour casts
693
fn normalize_u16(i: u16) -> u8 {
693
    ((f32::from(i) / f32::from(core::u16::MAX)) * f32::from(core::u8::MAX)) as u8
693
}
const FOUR_BPP: usize = 4;
const TWO_CHANNELS: usize = 2;
const THREE_CHANNELS: usize = 3;
const FOUR_CHANNELS: usize = 4;
impl RawImage {
    /// Returns a null / empty image
    #[must_use]
8
    pub fn null_image() -> Self {
8
        Self {
8
            pixels: RawImageData::U8(Vec::new().into()),
8
            width: 0,
8
            height: 0,
8
            premultiplied_alpha: true,
8
            data_format: RawImageFormat::BGRA8,
8
            tag: Vec::new().into(),
8
        }
8
    }
    /// Allocates a width * height, single-channel mask, used for drawing CPU image masks
    #[allow(clippy::cast_sign_loss)] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[must_use]
4
    pub fn allocate_mask(size: LayoutSize) -> Self {
4
        Self {
4
            pixels: RawImageData::U8(
4
                vec![0; size.width.max(0) as usize * size.height.max(0) as usize].into(),
4
            ),
4
            width: size.width as usize,
4
            height: size.height as usize,
4
            premultiplied_alpha: true,
4
            data_format: RawImageFormat::R8,
4
            tag: Vec::new().into(),
4
        }
4
    }
    /// Encodes a `RawImage` as BGRA8 bytes and premultiplies it if the alpha is not premultiplied
    ///
    /// Returns None if the width * height * BPP does not match
    ///
    /// TODO: autovectorization fails spectacularly, need to manually optimize!
    #[must_use]
1384
    pub fn into_loaded_image_source(self) -> Option<(ImageData, ImageDescriptor)> {
        let Self {
1384
            width,
1384
            height,
1384
            pixels,
1384
            data_format,
1384
            premultiplied_alpha,
1384
            tag,
1384
        } = self;
        // Checked: a width*height that overflows usize is not a real image; return
        // None rather than panicking (debug) / wrapping to a bogus length (release).
1384
        let expected_len = width.checked_mul(height)?;
        // …and neither is one whose BYTE count overflows. Every `load_*` below
        // scales this pixel count by its channel count (2, 3 or 4) to validate the
        // input buffer, and allocates a 4-byte-per-pixel BGRA output buffer, so a
        // pixel count that cannot survive `* 4` cannot describe a real image
        // either. Without this guard those multiplies wrapped in release (an empty
        // buffer then *validated* as a 2^31 x 2^31 image) and panicked in debug —
        // and because the callers are `extern "C"` widget callbacks, that panic is
        // a non-unwinding ABORT that `catch_unwind` cannot contain. One check here
        // covers all 20 multiplication sites.
1383
        expected_len.checked_mul(FOUR_BPP)?;
1359
        let (bytes, data_format, is_opaque): (U8Vec, RawImageFormat, bool) = match data_format {
            RawImageFormat::R8 => {
337
                let (bytes, is_opaque) = Self::load_r8(pixels, expected_len)?;
337
                (bytes, RawImageFormat::R8, is_opaque)
            }
            RawImageFormat::RG8 => {
                let (bytes, is_opaque) = Self::load_rg8(pixels, expected_len, premultiplied_alpha)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RGB8 => {
                let (bytes, is_opaque) = Self::load_rgb8(pixels, expected_len)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RGBA8 => {
802
                let (bytes, is_opaque) =
1009
                    Self::load_rgba8(pixels, expected_len, premultiplied_alpha)?;
802
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::R16 => {
                let (bytes, is_opaque) = Self::load_r16(pixels, expected_len)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RG16 => {
                let (bytes, is_opaque) = Self::load_rg16(pixels, expected_len)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RGB16 => {
                let (bytes, is_opaque) = Self::load_rgb16(pixels, expected_len)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RGBA16 => {
                let (bytes, is_opaque) =
                    Self::load_rgba16(pixels, expected_len, premultiplied_alpha)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::BGR8 => {
                let (bytes, is_opaque) = Self::load_bgr8(pixels, expected_len)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::BGRA8 => {
13
                let (bytes, is_opaque) =
13
                    Self::load_bgra8(pixels, expected_len, premultiplied_alpha)?;
13
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RGBF32 => {
                let (bytes, is_opaque) = Self::load_rgbf32(pixels, expected_len)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
            RawImageFormat::RGBAF32 => {
                let (bytes, is_opaque) =
                    Self::load_rgbaf32(pixels, expected_len, premultiplied_alpha)?;
                (bytes, RawImageFormat::BGRA8, is_opaque)
            }
        };
1152
        let image_data = ImageData::Raw(SharedRawImageData::new(bytes));
1152
        let image_descriptor = ImageDescriptor {
1152
            format: data_format,
1152
            width,
1152
            height,
1152
            offset: 0,
1152
            stride: None.into(),
1152
            flags: ImageDescriptorFlags {
1152
                is_opaque,
1152
                allow_mipmaps: true,
1152
            },
1152
        };
1152
        Some((image_data, image_descriptor))
1384
    }
    /// Keep R8 data as-is — `WebRender` supports R8 natively. This is important for
    /// image mask clips which need the single-channel data (white=visible,
    /// black=clipped). Stays in `R8` format; never opaque.
342
    fn load_r8(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
342
        let pixels = pixels.get_u8_vec()?;
341
        if pixels.len() != expected_len {
2
            return None;
339
        }
339
        Some((pixels, false))
342
    }
6
    fn load_rg8(
6
        pixels: RawImageData,
6
        expected_len: usize,
6
        premultiplied_alpha: bool,
6
    ) -> Option<(U8Vec, bool)> {
6
        let pixels = pixels.get_u8_vec()?;
5
        if pixels.len() != expected_len * TWO_CHANNELS {
2
            return None;
3
        }
3
        let mut is_opaque = true;
3
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
3
        for (pixel_index, greyalpha) in pixels.as_ref().chunks_exact(TWO_CHANNELS).enumerate() {
2
            let grey = greyalpha[0];
2
            let alpha = greyalpha[1];
2
            if alpha != 255 {
1
                is_opaque = false;
1
            }
2
            px[pixel_index * FOUR_BPP] = grey;
2
            px[(pixel_index * FOUR_BPP) + 1] = grey;
2
            px[(pixel_index * FOUR_BPP) + 2] = grey;
2
            px[(pixel_index * FOUR_BPP) + 3] = alpha;
2
            if !premultiplied_alpha {
1
                premultiply_alpha(
1
                    &mut px[(pixel_index * FOUR_BPP)..((pixel_index * FOUR_BPP) + FOUR_BPP)],
1
                );
1
            }
        }
3
        Some((px.into(), is_opaque))
6
    }
5
    fn load_rgb8(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
5
        let pixels = pixels.get_u8_vec()?;
4
        if pixels.len() != expected_len * THREE_CHANNELS {
2
            return None;
2
        }
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        for (pixel_index, rgb) in pixels.as_ref().chunks_exact(THREE_CHANNELS).enumerate() {
1
            let red = rgb[0];
1
            let green = rgb[1];
1
            let blue = rgb[2];
1

            
1
            px[pixel_index * FOUR_BPP] = blue;
1
            px[(pixel_index * FOUR_BPP) + 1] = green;
1
            px[(pixel_index * FOUR_BPP) + 2] = red;
1
            px[(pixel_index * FOUR_BPP) + 3] = 0xff;
1
        }
2
        Some((px.into(), true))
5
    }
1017
    fn load_rgba8(
1017
        pixels: RawImageData,
1017
        expected_len: usize,
1017
        premultiplied_alpha: bool,
1017
    ) -> Option<(U8Vec, bool)> {
1017
        let mut pixels: Vec<u8> = pixels.get_u8_vec()?.into_library_owned_vec();
1015
        if pixels.len() != expected_len * FOUR_CHANNELS {
208
            return None;
807
        }
807
        let mut is_opaque = true;
        // TODO: check that this function is SIMD optimized
        // no extra allocation necessary, but swizzling
807
        if premultiplied_alpha {
1591
            for rgba in pixels.chunks_exact_mut(4) {
1591
                let (r, gba) = rgba.split_first_mut()?;
1591
                core::mem::swap(r, gba.get_mut(1)?);
1591
                let a = rgba.get_mut(3)?;
1591
                if *a != 255 {
1589
                    is_opaque = false;
1589
                }
            }
        } else {
50589251
            for rgba in pixels.chunks_exact_mut(4) {
                // RGBA => BGRA
50589251
                let (r, gba) = rgba.split_first_mut()?;
50589251
                core::mem::swap(r, gba.get_mut(1)?);
50589251
                let a = rgba.get_mut(3)?;
50589251
                if *a != 255 {
17305075
                    is_opaque = false;
33284183
                }
50589251
                premultiply_alpha(rgba); // <-
            }
        }
807
        Some((pixels.into(), is_opaque))
1017
    }
4
    fn load_r16(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
4
        let pixels = pixels.get_u16_vec()?;
3
        if pixels.len() != expected_len {
1
            return None;
2
        }
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        for (pixel_index, grey_u16) in pixels.as_ref().iter().enumerate() {
1
            let grey_u8 = normalize_u16(*grey_u16);
1
            px[pixel_index * FOUR_BPP] = grey_u8;
1
            px[(pixel_index * FOUR_BPP) + 1] = grey_u8;
1
            px[(pixel_index * FOUR_BPP) + 2] = grey_u8;
1
            px[(pixel_index * FOUR_BPP) + 3] = 0xff;
1
        }
2
        Some((px.into(), true))
4
    }
4
    fn load_rg16(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
4
        let pixels = pixels.get_u16_vec()?;
3
        if pixels.len() != expected_len * TWO_CHANNELS {
1
            return None;
2
        }
2
        let mut is_opaque = true;
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        for (pixel_index, greyalpha) in pixels.as_ref().chunks_exact(TWO_CHANNELS).enumerate() {
1
            let grey_u8 = normalize_u16(greyalpha[0]);
1
            let alpha_u8 = normalize_u16(greyalpha[1]);
1
            if alpha_u8 != 255 {
                is_opaque = false;
1
            }
1
            px[pixel_index * FOUR_BPP] = grey_u8;
1
            px[(pixel_index * FOUR_BPP) + 1] = grey_u8;
1
            px[(pixel_index * FOUR_BPP) + 2] = grey_u8;
1
            px[(pixel_index * FOUR_BPP) + 3] = alpha_u8;
        }
2
        Some((px.into(), is_opaque))
4
    }
4
    fn load_rgb16(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
4
        let pixels = pixels.get_u16_vec()?;
3
        if pixels.len() != expected_len * THREE_CHANNELS {
1
            return None;
2
        }
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        for (pixel_index, rgb) in pixels.as_ref().chunks_exact(THREE_CHANNELS).enumerate() {
1
            let red_u8 = normalize_u16(rgb[0]);
1
            let green_u8 = normalize_u16(rgb[1]);
1
            let blue_u8 = normalize_u16(rgb[2]);
1

            
1
            px[pixel_index * FOUR_BPP] = blue_u8;
1
            px[(pixel_index * FOUR_BPP) + 1] = green_u8;
1
            px[(pixel_index * FOUR_BPP) + 2] = red_u8;
1
            px[(pixel_index * FOUR_BPP) + 3] = 0xff;
1
        }
2
        Some((px.into(), true))
4
    }
4
    fn load_rgba16(
4
        pixels: RawImageData,
4
        expected_len: usize,
4
        premultiplied_alpha: bool,
4
    ) -> Option<(U8Vec, bool)> {
4
        let pixels = pixels.get_u16_vec()?;
3
        if pixels.len() != expected_len * FOUR_CHANNELS {
1
            return None;
2
        }
2
        let mut is_opaque = true;
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        if premultiplied_alpha {
1
            for (pixel_index, rgba) in pixels.as_ref().chunks_exact(FOUR_CHANNELS).enumerate() {
                let red_u8 = normalize_u16(rgba[0]);
                let green_u8 = normalize_u16(rgba[1]);
                let blue_u8 = normalize_u16(rgba[2]);
                let alpha_u8 = normalize_u16(rgba[3]);
                if alpha_u8 != 255 {
                    is_opaque = false;
                }
                px[pixel_index * FOUR_BPP] = blue_u8;
                px[(pixel_index * FOUR_BPP) + 1] = green_u8;
                px[(pixel_index * FOUR_BPP) + 2] = red_u8;
                px[(pixel_index * FOUR_BPP) + 3] = alpha_u8;
            }
        } else {
1
            for (pixel_index, rgba) in pixels.as_ref().chunks_exact(FOUR_CHANNELS).enumerate() {
1
                let red_u8 = normalize_u16(rgba[0]);
1
                let green_u8 = normalize_u16(rgba[1]);
1
                let blue_u8 = normalize_u16(rgba[2]);
1
                let alpha_u8 = normalize_u16(rgba[3]);
1
                if alpha_u8 != 255 {
1
                    is_opaque = false;
1
                }
1
                px[pixel_index * FOUR_BPP] = blue_u8;
1
                px[(pixel_index * FOUR_BPP) + 1] = green_u8;
1
                px[(pixel_index * FOUR_BPP) + 2] = red_u8;
1
                px[(pixel_index * FOUR_BPP) + 3] = alpha_u8;
1
                premultiply_alpha(
1
                    &mut px[(pixel_index * FOUR_BPP)..((pixel_index * FOUR_BPP) + FOUR_BPP)],
                );
            }
        }
2
        Some((px.into(), is_opaque))
4
    }
4
    fn load_bgr8(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
4
        let pixels = pixels.get_u8_vec()?;
3
        if pixels.len() != expected_len * THREE_CHANNELS {
1
            return None;
2
        }
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        for (pixel_index, bgr) in pixels.as_ref().chunks_exact(THREE_CHANNELS).enumerate() {
1
            let blue = bgr[0];
1
            let green = bgr[1];
1
            let red = bgr[2];
1

            
1
            px[pixel_index * FOUR_BPP] = blue;
1
            px[(pixel_index * FOUR_BPP) + 1] = green;
1
            px[(pixel_index * FOUR_BPP) + 2] = red;
1
            px[(pixel_index * FOUR_BPP) + 3] = 0xff;
1
        }
2
        Some((px.into(), true))
4
    }
19
    fn load_bgra8(
19
        pixels: RawImageData,
19
        expected_len: usize,
19
        premultiplied_alpha: bool,
19
    ) -> Option<(U8Vec, bool)> {
19
        let mut is_opaque = true;
19
        let bytes: U8Vec = if premultiplied_alpha {
            // DO NOT CLONE THE IMAGE HERE!
5
            let pixels = pixels.get_u8_vec()?;
4
            if pixels.len() != expected_len * FOUR_BPP {
1
                return None;
3
            }
3
            is_opaque = pixels
3
                .as_ref()
3
                .chunks_exact(FOUR_CHANNELS)
4
                .all(|bgra| bgra[3] == 255);
3
            pixels
        } else {
14
            let mut pixels: Vec<u8> = pixels.get_u8_vec()?.into_library_owned_vec();
14
            if pixels.len() != expected_len * FOUR_BPP {
2
                return None;
12
            }
120000
            for bgra in pixels.chunks_exact_mut(FOUR_CHANNELS) {
120000
                if bgra[3] != 255 {
                    is_opaque = false;
120000
                }
120000
                premultiply_alpha(bgra);
            }
12
            pixels.into()
        };
15
        Some((bytes, is_opaque))
19
    }
    #[allow(clippy::cast_possible_truncation)] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[allow(clippy::cast_sign_loss)] // image/graphics: bounded pixel/colour casts
    #[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API /
                                             // ownership-transfer convention)
4
    fn load_rgbf32(pixels: RawImageData, expected_len: usize) -> Option<(U8Vec, bool)> {
4
        let pixels = pixels.get_f32_vec_ref()?;
3
        if pixels.len() != expected_len * THREE_CHANNELS {
1
            return None;
2
        }
2
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
2
        for (pixel_index, rgb) in pixels.as_ref().chunks_exact(THREE_CHANNELS).enumerate() {
1
            let red_u8 = (rgb[0] * 255.0) as u8;
1
            let green_u8 = (rgb[1] * 255.0) as u8;
1
            let blue_u8 = (rgb[2] * 255.0) as u8;
1

            
1
            px[pixel_index * FOUR_BPP] = blue_u8;
1
            px[(pixel_index * FOUR_BPP) + 1] = green_u8;
1
            px[(pixel_index * FOUR_BPP) + 2] = red_u8;
1
            px[(pixel_index * FOUR_BPP) + 3] = 0xff;
1
        }
2
        Some((px.into(), true))
4
    }
    #[allow(clippy::cast_possible_truncation)] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[allow(clippy::cast_sign_loss)] // image/graphics: bounded pixel/colour casts
    #[allow(clippy::needless_pass_by_value)] // owned RawImageData taken by value (image decode
                                             // entry point)
5
    fn load_rgbaf32(
5
        pixels: RawImageData,
5
        expected_len: usize,
5
        premultiplied_alpha: bool,
5
    ) -> Option<(U8Vec, bool)> {
5
        let pixels = pixels.get_f32_vec_ref()?;
4
        if pixels.len() != expected_len * FOUR_CHANNELS {
1
            return None;
3
        }
3
        let mut is_opaque = true;
3
        let mut px = vec![0; expected_len * FOUR_BPP];
        // TODO: check that this function is SIMD optimized
3
        if premultiplied_alpha {
3
            for (pixel_index, rgba) in pixels.as_ref().chunks_exact(FOUR_CHANNELS).enumerate() {
2
                let red_u8 = (rgba[0] * 255.0) as u8;
2
                let green_u8 = (rgba[1] * 255.0) as u8;
2
                let blue_u8 = (rgba[2] * 255.0) as u8;
2
                let alpha_u8 = (rgba[3] * 255.0) as u8;
2
                if alpha_u8 != 255 {
1
                    is_opaque = false;
1
                }
2
                px[pixel_index * FOUR_BPP] = blue_u8;
2
                px[(pixel_index * FOUR_BPP) + 1] = green_u8;
2
                px[(pixel_index * FOUR_BPP) + 2] = red_u8;
2
                px[(pixel_index * FOUR_BPP) + 3] = alpha_u8;
            }
        } else {
            for (pixel_index, rgba) in pixels.as_ref().chunks_exact(FOUR_CHANNELS).enumerate() {
                let red_u8 = (rgba[0] * 255.0) as u8;
                let green_u8 = (rgba[1] * 255.0) as u8;
                let blue_u8 = (rgba[2] * 255.0) as u8;
                let alpha_u8 = (rgba[3] * 255.0) as u8;
                if alpha_u8 != 255 {
                    is_opaque = false;
                }
                px[pixel_index * FOUR_BPP] = blue_u8;
                px[(pixel_index * FOUR_BPP) + 1] = green_u8;
                px[(pixel_index * FOUR_BPP) + 2] = red_u8;
                px[(pixel_index * FOUR_BPP) + 3] = alpha_u8;
                premultiply_alpha(
                    &mut px[(pixel_index * FOUR_BPP)..((pixel_index * FOUR_BPP) + FOUR_BPP)],
                );
            }
        }
3
        Some((px.into(), is_opaque))
5
    }
}
impl_option!(
    RawImage,
    OptionRawImage,
    copy = false,
    [Debug, Clone, PartialEq, PartialOrd]
);
#[must_use]
41
pub fn font_size_to_au(font_size: StyleFontSize) -> Au {
41
    Au::from_px(
41
        font_size
41
            .inner
41
            .to_pixels_internal(0.0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
    )
41
}
pub type FontInstanceFlags = u32;
// Common flags
pub const FONT_INSTANCE_FLAG_SYNTHETIC_BOLD: u32 = 1 << 1;
pub const FONT_INSTANCE_FLAG_EMBEDDED_BITMAPS: u32 = 1 << 2;
pub const FONT_INSTANCE_FLAG_SUBPIXEL_BGR: u32 = 1 << 3;
pub const FONT_INSTANCE_FLAG_TRANSPOSE: u32 = 1 << 4;
pub const FONT_INSTANCE_FLAG_FLIP_X: u32 = 1 << 5;
pub const FONT_INSTANCE_FLAG_FLIP_Y: u32 = 1 << 6;
pub const FONT_INSTANCE_FLAG_SUBPIXEL_POSITION: u32 = 1 << 7;
// Windows flags
pub const FONT_INSTANCE_FLAG_FORCE_GDI: u32 = 1 << 16;
// Mac flags
pub const FONT_INSTANCE_FLAG_FONT_SMOOTHING: u32 = 1 << 16;
// FreeType flags
pub const FONT_INSTANCE_FLAG_FORCE_AUTOHINT: u32 = 1 << 16;
pub const FONT_INSTANCE_FLAG_NO_AUTOHINT: u32 = 1 << 17;
pub const FONT_INSTANCE_FLAG_VERTICAL_LAYOUT: u32 = 1 << 18;
pub const FONT_INSTANCE_FLAG_LCD_VERTICAL: u32 = 1 << 19;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct GlyphOptions {
    pub render_mode: FontRenderMode,
    pub flags: FontInstanceFlags,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum FontRenderMode {
    Mono,
    Alpha,
    Subpixel,
}
#[cfg(target_arch = "wasm32")]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct FontInstancePlatformOptions {
    // empty for now
}
#[cfg(target_os = "windows")]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct FontInstancePlatformOptions {
    pub gamma: u16,
    pub contrast: u8,
    pub cleartype_level: u8,
}
#[cfg(target_os = "macos")]
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct FontInstancePlatformOptions {
    pub unused: u32,
}
#[cfg(target_os = "linux")]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct FontInstancePlatformOptions {
    pub lcd_filter: FontLCDFilter,
    pub hinting: FontHinting,
}
// Mobile targets — empty platform-options struct keeps the
// `FontInstanceOptions { platform_options: Option<...>, .. }` field
// well-typed without inheriting Linux's freetype-specific tunables.
#[cfg(any(target_os = "android", target_os = "ios"))]
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct FontInstancePlatformOptions {
    pub unused: u32,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum FontHinting {
    None,
    Mono,
    Light,
    Normal,
    LCD,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
pub enum FontLCDFilter {
    None,
    #[default]
    Default,
    Light,
    Legacy,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct FontInstanceOptions {
    pub render_mode: FontRenderMode,
    pub flags: FontInstanceFlags,
    pub bg_color: ColorU,
    /// When `bg_color.a` is != 0 and `render_mode` is `FontRenderMode::Subpixel`,
    /// the text will be rendered with `bg_color.r/g/b` as an opaque estimated
    /// background color.
    pub synthetic_italics: SyntheticItalics,
}
impl Default for FontInstanceOptions {
2
    fn default() -> Self {
2
        Self {
2
            render_mode: FontRenderMode::Subpixel,
2
            flags: 0,
2
            bg_color: ColorU::TRANSPARENT,
2
            synthetic_italics: SyntheticItalics::default(),
2
        }
2
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
pub struct SyntheticItalics {
    pub angle: i16,
}
/// Reference-counted wrapper around raw image bytes (`U8Vec`).
/// This allows sharing image data between azul-core and webrender without cloning.
///
/// Similar to `ImageRef` but specifically for raw byte data, avoiding the overhead
/// of the full `DecodedImage` enum when we just need the bytes.
#[derive(Debug)]
#[repr(C)]
pub struct SharedRawImageData {
    /// Shared pointer to the raw image bytes
    pub data: *const U8Vec,
    /// Reference counter - when it reaches 0, the data is deallocated
    pub copies: *const AtomicUsize,
    /// Whether to run the destructor (for FFI safety)
    pub run_destructor: bool,
}
impl SharedRawImageData {
    /// Create a new `SharedRawImageData` from a `U8Vec`
    #[must_use]
1159
    pub fn new(data: U8Vec) -> Self {
1159
        Self {
1159
            data: Box::into_raw(Box::new(data)),
1159
            copies: Box::into_raw(Box::new(AtomicUsize::new(1))),
1159
            run_destructor: true,
1159
        }
1159
    }
    /// Get a reference to the underlying bytes
    #[must_use]
465
    pub fn as_ref(&self) -> &[u8] {
        // SAFETY: `data` is a non-null, live `Box<U8Vec>` owned by this handle (and its
        // clones) until the last copy drops; the borrow is tied to `&self`.
465
        unsafe { (*self.data).as_ref() }
465
    }
    /// Alias for `as_ref()` - get the raw bytes as a slice
    #[must_use]
2
    pub fn get_bytes(&self) -> &[u8] {
2
        self.as_ref()
2
    }
    /// Get a pointer to the raw bytes for hashing/identification
    #[must_use]
5
    pub fn as_ptr(&self) -> *const u8 {
        // SAFETY: `data` is a non-null, live `Box<U8Vec>` (see `as_ref`).
5
        unsafe { (*self.data).as_ref().as_ptr() }
5
    }
    /// Get the length of the data
    #[must_use]
10
    pub const fn len(&self) -> usize {
        // SAFETY: `data` is a non-null, live `Box<U8Vec>` (see `as_ref`).
10
        unsafe { (*self.data).len() }
10
    }
    /// Check if the data is empty
    #[must_use]
5
    pub const fn is_empty(&self) -> bool {
5
        self.len() == 0
5
    }
    /// Try to extract the `U8Vec` if this is the only reference
    /// Returns None if there are other references
    #[must_use]
4
    pub fn into_inner(self) -> Option<U8Vec> {
        // SAFETY: `data`/`copies` are non-null heap allocations from `Box::into_raw` in
        // `new()`. When `copies == 1` we are the sole owner, so reclaiming both Boxes
        // and `forget`-ing `self` transfers ownership without a double free.
        unsafe {
4
            if self.copies.as_ref().map(|m| m.load(AtomicOrdering::SeqCst)) == Some(1) {
2
                let data = Box::from_raw(self.data.cast_mut());
2
                drop(Box::from_raw(self.copies.cast_mut()));
2
                core::mem::forget(self); // don't run the destructor
2
                Some(*data)
            } else {
2
                None
            }
        }
4
    }
}
// SAFETY: the raw pointers only address heap `Box`es of `Send`/`Sync` data, and all
// cross-thread refcount mutation goes through the `AtomicUsize` in `copies`.
unsafe impl Send for SharedRawImageData {}
unsafe impl Sync for SharedRawImageData {}
impl Clone for SharedRawImageData {
6
    fn clone(&self) -> Self {
        // SAFETY: `copies` is a non-null, live `AtomicUsize` shared by all clones; the
        // atomic increment balances the `fetch_sub` in `Drop`.
        unsafe {
6
            self.copies
6
                .as_ref()
6
                .map(|m| m.fetch_add(1, AtomicOrdering::SeqCst));
        }
6
        Self {
6
            data: self.data,
6
            copies: self.copies,
6
            run_destructor: true,
6
        }
6
    }
}
impl Drop for SharedRawImageData {
1163
    fn drop(&mut self) {
1163
        self.run_destructor = false;
        // SAFETY: `data`/`copies` are non-null, live `Box`es shared by all clones.
        // `fetch_sub` returns the pre-decrement count, so `== 1` means we are the last
        // owner; only then do we reclaim both Boxes exactly once.
        unsafe {
1163
            let copies = (*self.copies).fetch_sub(1, AtomicOrdering::SeqCst);
1163
            if copies == 1 {
1157
                drop(Box::from_raw(self.data.cast_mut()));
1157
                drop(Box::from_raw(self.copies.cast_mut()));
1157
            }
        }
1163
    }
}
impl PartialEq for SharedRawImageData {
1
    fn eq(&self, rhs: &Self) -> bool {
1
        core::ptr::eq(self.data, rhs.data)
1
    }
}
impl Eq for SharedRawImageData {}
impl PartialOrd for SharedRawImageData {
    fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for SharedRawImageData {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.data as usize).cmp(&(other.data as usize))
    }
}
impl Hash for SharedRawImageData {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        (self.data as usize).hash(state);
    }
}
/// Represents the backing store of an arbitrary series of pixels for display by
/// `WebRender`. This storage can take several forms.
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(C, u8)]
pub enum ImageData {
    /// A simple series of bytes, provided by the embedding and owned by `WebRender`.
    /// The format is stored out-of-band, currently in `ImageDescriptor`.
    Raw(SharedRawImageData),
    /// An image owned by the embedding, and referenced by `WebRender`. This may
    /// take the form of a texture or a heap-allocated buffer.
    External(ExternalImageData),
}
/// Storage format identifier for externally-managed images.
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[repr(C, u8)]
pub enum ExternalImageType {
    /// The image is texture-backed.
    TextureHandle(ImageBufferKind),
    /// The image is heap-allocated by the embedding.
    Buffer,
}
/// An arbitrary identifier for an external image provided by the
/// application. It must be a unique identifier for each external
/// image.
#[repr(C)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct ExternalImageId {
    pub inner: u64,
}
static LAST_EXTERNAL_IMAGE_ID: AtomicUsize = AtomicUsize::new(0);
impl Default for ExternalImageId {
1
    fn default() -> Self {
1
        Self::new()
1
    }
}
impl ExternalImageId {
    /// Creates a new, unique `ExternalImageId`
8
    pub fn new() -> Self {
8
        Self {
8
            inner: LAST_EXTERNAL_IMAGE_ID.fetch_add(1, AtomicOrdering::SeqCst) as u64,
8
        }
8
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C, u8)]
pub enum GlyphOutlineOperation {
    MoveTo(OutlineMoveTo),
    LineTo(OutlineLineTo),
    QuadraticCurveTo(OutlineQuadTo),
    CubicCurveTo(OutlineCubicTo),
    ClosePath,
}
impl_option!(
    GlyphOutlineOperation,
    OptionGlyphOutlineOperation,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd]
);
// MoveTo in em units
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct OutlineMoveTo {
    pub x: i16,
    pub y: i16,
}
// LineTo in em units
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct OutlineLineTo {
    pub x: i16,
    pub y: i16,
}
// QuadTo in em units
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct OutlineQuadTo {
    pub ctrl_1_x: i16,
    pub ctrl_1_y: i16,
    pub end_x: i16,
    pub end_y: i16,
}
// CubicTo in em units
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct OutlineCubicTo {
    pub ctrl_1_x: i16,
    pub ctrl_1_y: i16,
    pub ctrl_2_x: i16,
    pub ctrl_2_y: i16,
    pub end_x: i16,
    pub end_y: i16,
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct GlyphOutline {
    pub operations: GlyphOutlineOperationVec,
}
azul_css::impl_vec!(
    GlyphOutlineOperation,
    GlyphOutlineOperationVec,
    GlyphOutlineOperationVecDestructor,
    GlyphOutlineOperationVecDestructorType,
    GlyphOutlineOperationVecSlice,
    OptionGlyphOutlineOperation
);
azul_css::impl_vec_clone!(
    GlyphOutlineOperation,
    GlyphOutlineOperationVec,
    GlyphOutlineOperationVecDestructor
);
azul_css::impl_vec_debug!(GlyphOutlineOperation, GlyphOutlineOperationVec);
azul_css::impl_vec_partialord!(GlyphOutlineOperation, GlyphOutlineOperationVec);
azul_css::impl_vec_partialeq!(GlyphOutlineOperation, GlyphOutlineOperationVec);
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct OwnedGlyphBoundingBox {
    pub max_x: i16,
    pub max_y: i16,
    pub min_x: i16,
    pub min_y: i16,
}
/// Specifies the type of texture target in driver terms.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[repr(C)]
pub enum ImageBufferKind {
    /// Standard texture. This maps to `GL_TEXTURE_2D` in OpenGL.
    Texture2D = 0,
    /// Rectangle texture. This maps to `GL_TEXTURE_RECTANGLE` in OpenGL. This
    /// is similar to a standard texture, with a few subtle differences
    /// (no mipmaps, non-power-of-two dimensions, different coordinate space)
    /// that make it useful for representing the kinds of textures we use
    /// in `WebRender`. See <https://www.khronos.org/opengl/wiki/Rectangle_Texture>
    /// for background on Rectangle textures.
    TextureRect = 1,
    /// External texture. This maps to `GL_TEXTURE_EXTERNAL_OES` in OpenGL, which
    /// is an extension. This is used for image formats that OpenGL doesn't
    /// understand, particularly YUV. See
    /// <https://www.khronos.org/registry/OpenGL/extensions/OES/OES_EGL_image_external.txt>
    TextureExternal = 2,
}
/// Descriptor for external image resources. See `ImageData`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct ExternalImageData {
    /// The identifier of this external image, provided by the embedding.
    pub id: ExternalImageId,
    /// For multi-plane images (i.e. YUV), indicates the plane of the
    /// original image that this struct represents. 0 for single-plane images.
    pub channel_index: u8,
    /// Storage format identifier.
    pub image_type: ExternalImageType,
}
pub type TileSize = u16;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
pub enum ImageDirtyRect {
    All,
    Partial(LayoutRect),
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum ResourceUpdate {
    AddFont(AddFont),
    DeleteFont(FontKey),
    AddFontInstance(AddFontInstance),
    DeleteFontInstance(FontInstanceKey),
    AddImage(AddImage),
    UpdateImage(UpdateImage),
    DeleteImage(ImageKey),
}
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct AddImage {
    pub key: ImageKey,
    pub descriptor: ImageDescriptor,
    pub data: ImageData,
    pub tiling: Option<TileSize>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub struct UpdateImage {
    pub key: ImageKey,
    pub descriptor: ImageDescriptor,
    pub data: ImageData,
    pub dirty_rect: ImageDirtyRect,
}
/// Message to add a font to `WebRender`.
/// Contains a reference to the parsed font data.
#[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct AddFont {
    pub key: FontKey,
    pub font: FontRef,
}
impl fmt::Debug for AddFont {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "AddFont {{ key: {:?}, font: {:?} }}",
            self.key, self.font
        )
    }
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct AddFontInstance {
    pub key: FontInstanceKey,
    pub font_key: FontKey,
    pub glyph_size: (Au, DpiScaleFactor),
    pub options: Option<FontInstanceOptions>,
    pub platform_options: Option<FontInstancePlatformOptions>,
    pub variations: Vec<FontVariation>,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialOrd, PartialEq)]
pub struct FontVariation {
    pub tag: u32,
    pub value: f32,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Epoch {
    inner: u32,
}
impl fmt::Display for Epoch {
3
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3
        write!(f, "{}", self.inner)
3
    }
}
impl Default for Epoch {
2
    fn default() -> Self {
2
        Self::new()
2
    }
}
impl Epoch {
    // prevent raw access to the .inner field so that
    // you can grep the codebase for .increment() to see
    // exactly where the epoch is being incremented
    #[must_use]
29060
    pub const fn new() -> Self {
29060
        Self { inner: 0 }
29060
    }
    #[must_use]
22
    pub const fn from(i: u32) -> Self {
22
        Self { inner: i }
22
    }
    #[must_use]
17
    pub const fn into_u32(&self) -> u32 {
17
        self.inner
17
    }
    // We don't want the epoch to increase to u32::MAX, since
    // u32::MAX represents an invalid epoch, which could confuse webrender
11
    pub const fn increment(&mut self) {
        use core::u32;
        const MAX_ID: u32 = u32::MAX - 1;
11
        *self = match self.inner {
2
            MAX_ID => Self { inner: 0 },
9
            other => Self {
9
                inner: other.saturating_add(1),
9
            },
        };
11
    }
}
// App units that this font instance was registered for
#[derive(Debug, Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)]
pub struct Au(pub i32);
pub const AU_PER_PX: i32 = 60;
pub const MAX_AU: i32 = (1 << 30) - 1;
pub const MIN_AU: i32 = -(1 << 30) - 1;
impl Au {
    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[must_use]
75
    pub fn from_px(px: f32) -> Self {
75
        let target_app_units = (px * AU_PER_PX as f32) as i32;
75
        Self(target_app_units.clamp(MIN_AU, MAX_AU))
75
    }
    #[allow(clippy::cast_precision_loss)] // image/graphics: bounded pixel/colour/dimension/unit casts
    #[must_use]
13
    pub fn into_px(&self) -> f32 {
13
        self.0 as f32 / AU_PER_PX as f32
13
    }
}
// Debug, PartialEq, Eq, PartialOrd, Ord
#[derive(Debug)]
pub enum AddFontMsg {
    // add font: font key, font bytes + font index
    Font(FontKey, StyleFontFamilyHash, FontRef),
    Instance(AddFontInstance, (Au, DpiScaleFactor)),
}
impl AddFontMsg {
    #[must_use]
4
    pub fn into_resource_update(&self) -> ResourceUpdate {
        use self::AddFontMsg::{Font, Instance};
4
        match self {
2
            Font(font_key, _, font_ref) => ResourceUpdate::AddFont(AddFont {
2
                key: *font_key,
2
                font: font_ref.clone(),
2
            }),
2
            Instance(fi, _) => ResourceUpdate::AddFontInstance(fi.clone()),
        }
4
    }
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum DeleteFontMsg {
    Font(FontKey),
    Instance(FontInstanceKey, (Au, DpiScaleFactor)),
}
impl DeleteFontMsg {
    #[must_use]
2
    pub const fn into_resource_update(&self) -> ResourceUpdate {
        use self::DeleteFontMsg::{Font, Instance};
2
        match self {
1
            Font(f) => ResourceUpdate::DeleteFont(*f),
1
            Instance(fi, _) => ResourceUpdate::DeleteFontInstance(*fi),
        }
2
    }
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct AddImageMsg(pub AddImage);
impl AddImageMsg {
    #[must_use]
2
    pub fn into_resource_update(&self) -> ResourceUpdate {
2
        ResourceUpdate::AddImage(self.0.clone())
2
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct LoadedFontSource {
    pub data: U8Vec,
    pub index: u32,
    pub load_outlines: bool,
}
// function to load the font source from a file
pub type LoadFontFn = fn(&StyleFontFamily, &FcFontCache) -> Option<LoadedFontSource>;
// function to parse the font given the loaded font source
pub type ParseFontFn = fn(LoadedFontSource) -> Option<FontRef>; // = Option<Box<azul_text_layout::Font>>
pub type GlStoreImageFn = fn(DocumentId, Epoch, Texture, ExternalImageId);
/// Compute the deterministic `ExternalImageId` that the OpenGL texture cache uses
/// for a texture bound to a specific DOM node.
///
/// The same `(DomId, NodeId)` always
/// maps to the same `ExternalImageId`, so cached display lists keep working across
/// frames.
#[must_use]
8
pub fn texture_external_image_id(dom_id: DomId, node_id: NodeId) -> ExternalImageId {
8
    let dom = dom_id.inner as u64;
8
    let node = node_id.index() as u64;
8
    debug_assert!(u32::try_from(dom).is_ok(), "DomId exceeds 32-bit range");
8
    debug_assert!(u32::try_from(node).is_ok(), "NodeId exceeds 32-bit range");
8
    ExternalImageId {
8
        inner: (dom << 32) | (node & 0xFFFF_FFFF),
8
    }
8
}
/// Compute the `ExternalImageId` for a static GL texture identified by its
/// `ImageRefHash`. Mirrors `image_ref_hash_to_image_key` so a given image hash
/// produces the same identifiers everywhere.
#[must_use]
5
pub const fn image_ref_hash_to_external_image_id(hash: ImageRefHash) -> ExternalImageId {
5
    ExternalImageId { inner: hash.inner }
5
}
/// Given the fonts of the current frame, returns `AddFont` and `AddFontInstance`s of
/// which fonts / instances are currently not in the `current_registered_fonts` and
/// need to be added.
///
/// Deleting fonts can only be done after the entire frame has finished drawing,
/// otherwise (if removing fonts would happen after every DOM) we'd constantly
/// add-and-remove fonts after every `VirtualViewCallback`, which would cause a lot of
/// I/O waiting.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one
                                 // branch per input variant)
4
pub fn build_add_font_resource_updates(
4
    renderer_resources: &mut RendererResources,
4
    dpi: DpiScaleFactor,
4
    fc_cache: &FcFontCache,
4
    id_namespace: IdNamespace,
4
    fonts_in_dom: &OrderedMap<ImmediateFontId, FastBTreeSet<Au>>,
4
    font_source_load_fn: LoadFontFn,
4
    parse_font_fn: ParseFontFn,
4
) -> Vec<(StyleFontFamilyHash, AddFontMsg)> {
4
    let mut resource_updates = Vec::new();
4
    let mut font_instances_added_this_frame = FastBTreeSet::new();
7
    'outer: for (im_font_id, font_sizes) in fonts_in_dom {
        macro_rules! insert_font_instances {
            ($font_family_hash:expr, $font_key:expr, $font_size:expr) => {{
                let font_instance_key_exists = renderer_resources
                    .currently_registered_fonts
                    .get(&$font_key)
2
                    .and_then(|(_, font_instances)| font_instances.get(&($font_size, dpi)))
                    .is_some()
                    || font_instances_added_this_frame.contains(&($font_key, ($font_size, dpi)));
                if !font_instance_key_exists {
                    let font_instance_key = FontInstanceKey::unique(id_namespace);
                    // For some reason the gamma is way to low on Windows
                    #[cfg(target_os = "windows")]
                    let platform_options = FontInstancePlatformOptions {
                        gamma: 300,
                        contrast: 100,
                        cleartype_level: 100,
                    };
                    #[cfg(target_os = "linux")]
                    let platform_options = FontInstancePlatformOptions {
                        lcd_filter: FontLCDFilter::Default,
                        hinting: FontHinting::Normal,
                    };
                    #[cfg(target_os = "macos")]
                    let platform_options = FontInstancePlatformOptions::default();
                    #[cfg(target_arch = "wasm32")]
                    let platform_options = FontInstancePlatformOptions::default();
                    #[cfg(any(target_os = "android", target_os = "ios"))]
                    let platform_options = FontInstancePlatformOptions::default();
                    let options = FontInstanceOptions {
                        render_mode: FontRenderMode::Subpixel,
                        flags: FONT_INSTANCE_FLAG_NO_AUTOHINT,
                        ..Default::default()
                    };
                    font_instances_added_this_frame.insert(($font_key, ($font_size, dpi)));
                    resource_updates.push((
                        $font_family_hash,
                        AddFontMsg::Instance(
                            AddFontInstance {
                                key: font_instance_key,
                                font_key: $font_key,
                                glyph_size: ($font_size, dpi),
                                options: Some(options),
                                platform_options: Some(platform_options),
                                variations: alloc::vec::Vec::new(),
                            },
                            ($font_size, dpi),
                        ),
                    ));
                }
            }};
        }
3
        match im_font_id {
            ImmediateFontId::Resolved((font_family_hash, font_id)) => {
                // nothing to do, font is already added,
                // just insert the missing font instances
                for font_size in font_sizes {
                    insert_font_instances!(*font_family_hash, *font_id, *font_size);
                }
            }
3
            ImmediateFontId::Unresolved(style_font_families) => {
                // If the font is already loaded during the current frame,
                // do not attempt to load it again
                //
                // This prevents duplicated loading for fonts in different orders, i.e.
                // - vec!["Times New Roman", "serif"] and
                // - vec!["sans", "Times New Roman"]
                // ... will resolve to the same font instead of creating two fonts
                // If there is no font key, that means there's also no font instances
3
                let mut font_family_hash = None;
3
                let font_families_hash = StyleFontFamiliesHash::new(style_font_families.as_ref());
                // Find the first font that can be loaded and parsed
3
                'inner: for family in style_font_families.as_ref() {
3
                    let current_family_hash = StyleFontFamilyHash::new(family);
3
                    if let Some(font_id) = renderer_resources.font_id_map.get(&current_family_hash)
                    {
                        // font key already exists
3
                        for font_size in font_sizes {
2
                            insert_font_instances!(current_family_hash, *font_id, *font_size);
                        }
1
                        continue 'outer;
2
                    }
2
                    let font_ref = match family {
1
                        StyleFontFamily::Ref(r) => r.clone(), // Clone the FontRef
1
                        other => {
                            // Load and parse the font
1
                            let Some(font_data) = (font_source_load_fn)(other, fc_cache) else {
1
                                continue 'inner;
                            };
                            match (parse_font_fn)(font_data) {
                                Some(s) => s,
                                None => continue 'inner,
                            }
                        }
                    };
                    // font loaded properly
1
                    font_family_hash = Some((current_family_hash, font_ref));
1
                    break 'inner;
                }
                // No font could be loaded: try again next frame.
2
                let Some((font_family_hash, font_ref)) = font_family_hash else {
1
                    continue 'outer;
                };
                // Generate a new font key, store the mapping between hash and font key
1
                let font_key = FontKey::unique(id_namespace);
1
                let add_font_msg = AddFontMsg::Font(font_key, font_family_hash, font_ref);
1
                renderer_resources
1
                    .font_id_map
1
                    .insert(font_family_hash, font_key);
1
                renderer_resources
1
                    .font_families_map
1
                    .insert(font_families_hash, font_family_hash);
1
                resource_updates.push((font_family_hash, add_font_msg));
                // Insert font sizes for the newly generated font key
3
                for font_size in font_sizes {
2
                    insert_font_instances!(font_family_hash, font_key, *font_size);
                }
            }
        }
    }
4
    resource_updates
4
}
/// Given the images of the current frame, returns `AddImage`s of
/// which image keys are currently not in the `current_registered_images` and
/// need to be added.
///
/// Returns Vec<(`ImageRefHash`, `AddImageMsg`)> where:
/// - `ImageRefHash`: Stable hash of the `ImageRef` pointer
/// - `AddImageMsg`: Message to add the image to `WebRender`
///
/// The `ImageKey` in `AddImageMsg` is generated directly from the `ImageRefHash` using
/// `image_ref_hash_to_image_key()`, so no separate mapping table is needed.
///
/// Deleting images can only be done after the entire frame has finished drawing,
/// otherwise (if removing images would happen after every DOM) we'd constantly
/// add-and-remove images after every `VirtualViewCallback`, which would cause a lot of
/// I/O waiting.
#[allow(unused_variables)]
4
pub fn build_add_image_resource_updates(
4
    renderer_resources: &RendererResources,
4
    id_namespace: IdNamespace,
4
    epoch: Epoch,
4
    document_id: &DocumentId,
4
    images_in_dom: &FastBTreeSet<ImageRef>,
4
    insert_into_active_gl_textures: GlStoreImageFn,
4
) -> Vec<(ImageRefHash, AddImageMsg)> {
4
    images_in_dom
4
        .iter()
4
        .filter_map(|image_ref| {
4
            let image_ref_hash = image_ref_get_hash(image_ref);
4
            if renderer_resources
4
                .currently_registered_images
4
                .contains_key(&image_ref_hash)
            {
1
                return None;
3
            }
            // NOTE: The image_ref.clone() is a shallow clone,
            // does not actually clone the data
3
            match image_ref.get_data() {
                DecodedImage::Gl(texture) => {
                    let descriptor = texture.get_descriptor();
                    let key = image_ref_hash_to_image_key(image_ref_hash, id_namespace);
                    // The ExternalImageId is derived from the same stable hash that
                    // produces the ImageKey, so the GL texture cache and WebRender
                    // agree on a single identifier for this texture.
                    let external_image_id = image_ref_hash_to_external_image_id(image_ref_hash);
                    // NOTE: The texture is not really cloned here,
                    (insert_into_active_gl_textures)(
                        *document_id,
                        epoch,
                        texture.clone(),
                        external_image_id,
                    );
                    Some((
                        image_ref_hash,
                        AddImageMsg(AddImage {
                            key,
                            data: ImageData::External(ExternalImageData {
                                id: external_image_id,
                                channel_index: 0,
                                image_type: ExternalImageType::TextureHandle(
                                    ImageBufferKind::Texture2D,
                                ),
                            }),
                            descriptor,
                            tiling: None,
                        }),
                    ))
                }
1
                DecodedImage::Raw((descriptor, data)) => {
1
                    let key = image_ref_hash_to_image_key(image_ref_hash, id_namespace);
1
                    Some((
1
                        image_ref_hash,
1
                        AddImageMsg(AddImage {
1
                            key,
1
                            data: data.clone(), // deep-copy except in the &'static case
1
                            descriptor: *descriptor, /* deep-copy, but struct is not very
1
                                                 * large */
1
                            tiling: None,
1
                        }),
1
                    ))
                }
                // NullImage has nothing to upload; texture callbacks are handled after
                // layout is done.
2
                DecodedImage::NullImage { .. } | DecodedImage::Callback(_) => None,
            }
4
        })
4
        .collect()
4
}
/// Submits the `AddFont`, `AddFontInstance` and `AddImage` resources to the `RenderApi`.
///
/// Extends `currently_registered_images` and `currently_registered_fonts` by the
/// `last_frame_image_keys` and `last_frame_font_keys`, so that we don't lose track of
/// what font and image keys are currently in the API.
#[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API /
                                         // ownership-transfer convention)
3
pub fn add_resources(
3
    renderer_resources: &mut RendererResources,
3
    all_resource_updates: &mut Vec<ResourceUpdate>,
3
    add_font_resources: Vec<(StyleFontFamilyHash, AddFontMsg)>,
3
    add_image_resources: Vec<(ImageRefHash, AddImageMsg)>,
3
) {
3
    all_resource_updates.extend(
3
        add_font_resources
3
            .iter()
3
            .map(|(_, f)| f.into_resource_update()),
    );
3
    all_resource_updates.extend(
3
        add_image_resources
3
            .iter()
3
            .map(|(_, i)| i.into_resource_update()),
    );
4
    for (image_ref_hash, add_image_msg) in &add_image_resources {
1
        renderer_resources.currently_registered_images.insert(
1
            *image_ref_hash,
1
            ResolvedImage {
1
                key: add_image_msg.0.key,
1
                descriptor: add_image_msg.0.descriptor,
1
            },
1
        );
1
        // Keep the reverse lookup (`ImageKey` -> `ImageRefHash`) in sync with the
1
        // forward map so display-list translation can resolve keys back to hashes.
1
        renderer_resources
1
            .image_key_map
1
            .insert(add_image_msg.0.key, *image_ref_hash);
1
    }
6
    for (_, add_font_msg) in add_font_resources {
        use self::AddFontMsg::{Font, Instance};
3
        match add_font_msg {
1
            Font(fk, font_family_hash, font_ref) => {
1
                renderer_resources
1
                    .currently_registered_fonts
1
                    .entry(fk)
1
                    .or_insert_with(|| (font_ref.clone(), OrderedMap::default()));
                // CRITICAL: Map font_hash to FontKey so we can look it up during rendering
1
                renderer_resources
1
                    .font_hash_map
1
                    .insert(font_ref.get_hash(), fk);
            }
2
            Instance(fi, size) => {
2
                if let Some((_, instances)) = renderer_resources
2
                    .currently_registered_fonts
2
                    .get_mut(&fi.font_key)
2
                {
2
                    instances.insert(size, fi.key);
2
                }
            }
        }
    }
3
}
#[cfg(test)]
#[path = "resources_test.rs"]
mod resources_test;