1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Blinc Application Delegate
//!
//! The main entry point for Blinc applications.
use blinc_gpu::{FontRegistry, GpuRenderer, RendererConfig, TextRenderingContext};
use blinc_layout::prelude::*;
use blinc_layout::RenderTree;
use std::sync::{Arc, Mutex};
use crate::context::RenderContext;
use crate::error::{BlincError, Result};
/// Blinc application configuration
#[derive(Clone, Debug)]
pub struct BlincConfig {
/// Maximum primitives per batch
pub max_primitives: usize,
/// Maximum glass primitives per batch
pub max_glass_primitives: usize,
/// Maximum glyphs per batch
pub max_glyphs: usize,
/// MSAA sample count (1, 2, 4, or 8)
pub sample_count: u32,
}
impl Default for BlincConfig {
fn default() -> Self {
Self {
max_primitives: 10_000,
max_glass_primitives: 1_000,
max_glyphs: 50_000,
sample_count: 4, // 4x MSAA for path anti-aliasing
}
}
}
/// The main Blinc application
///
/// This is the primary interface for rendering Blinc UI.
/// It handles all GPU initialization and provides a clean API.
///
/// # Example
///
/// ```ignore
/// use blinc_app::prelude::*;
///
/// let app = BlincApp::new()?;
///
/// let ui = div()
/// .w(400.0).h(300.0)
/// .child(text("Hello!").size(24.0));
///
/// // Render to a texture - handles everything automatically
/// app.render(&ui, target_view, 400.0, 300.0)?;
/// ```
pub struct BlincApp {
ctx: RenderContext,
config: BlincConfig,
}
impl BlincApp {
/// Create a new Blinc application with default configuration
pub fn new() -> Result<Self> {
Self::with_config(BlincConfig::default())
}
/// Create a new Blinc application from an existing render context
///
/// This is used internally for platform-specific initialization (Android, iOS)
/// where the GPU setup is done differently.
pub(crate) fn from_context(ctx: RenderContext, config: BlincConfig) -> Self {
Self { ctx, config }
}
/// Create a new Blinc application with custom configuration
pub fn with_config(config: BlincConfig) -> Result<Self> {
// Create renderer with sample_count=1 for SDF pipelines.
// MSAA is handled separately via render_overlay_msaa for foreground paths.
let renderer_config = RendererConfig {
max_primitives: config.max_primitives,
max_glass_primitives: config.max_glass_primitives,
max_glyphs: config.max_glyphs,
sample_count: 1, // SDF pipelines always use single-sampled textures
texture_format: None,
unified_text_rendering: true,
..RendererConfig::default()
};
let renderer = pollster::block_on(GpuRenderer::new(renderer_config))
.map_err(|e| BlincError::GpuInit(e.to_string()))?;
let device = renderer.device_arc();
let queue = renderer.queue_arc();
let mut text_ctx = TextRenderingContext::new(device.clone(), queue.clone());
// Load system default font
for font_path in crate::system_font_paths() {
let path = std::path::Path::new(font_path);
if path.exists() {
if let Ok(data) = std::fs::read(path) {
let _ = text_ctx.load_font_data(data);
break;
}
}
}
// Preload common fonts that apps might use
// This ensures fonts are cached before render time
text_ctx.preload_fonts(&[
"Inter",
"Fira Code",
"Menlo",
"SF Mono",
"SF Pro",
"Roboto",
"Consolas",
"Monaco",
"Source Code Pro",
"JetBrains Mono",
]);
// Preload generic font weights (for system fallback fonts)
text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[400, 600, 700, 800, 900],
false,
);
text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[400, 600, 700, 800, 900],
true,
);
text_ctx.preload_generic_styles(blinc_gpu::GenericFont::Monospace, &[400, 700], false);
let ctx = RenderContext::new(renderer, text_ctx, device, queue, config.sample_count);
Ok(Self { ctx, config })
}
/// Render a UI element tree to a texture
///
/// This handles everything automatically:
/// - Computes layout
/// - Renders background elements
/// - Renders glass elements with backdrop blur
/// - Renders foreground elements on top
/// - Renders text at layout-computed positions
/// - Renders SVG icons at layout-computed positions
/// - Applies MSAA if configured
///
/// # Arguments
///
/// * `element` - The root UI element (created with `div()`, etc.)
/// * `target` - The texture view to render to
/// * `width` - Viewport width in pixels
/// * `height` - Viewport height in pixels
///
/// # Example
///
/// ```ignore
/// let ui = div().w(400.0).h(300.0)
/// .flex_col().gap(4.0)
/// .child(
/// div().glass().rounded(16.0)
/// .child(text("Hello!").size(24.0))
/// );
///
/// app.render(&ui, &target_view, 400.0, 300.0)?;
/// ```
pub fn render<E: ElementBuilder>(
&mut self,
element: &E,
target: &wgpu::TextureView,
width: f32,
height: f32,
) -> Result<()> {
let mut tree = RenderTree::from_element(element);
tree.compute_layout(width, height);
self.ctx
.render_tree(&tree, width as u32, height as u32, target)
}
/// Render a pre-computed render tree
///
/// Use this when you want to compute layout once and render multiple times.
pub fn render_tree(
&mut self,
tree: &RenderTree,
target: &wgpu::TextureView,
width: u32,
height: u32,
) -> Result<()> {
self.ctx.render_tree(tree, width, height, target)
}
/// Render a pre-computed render tree with dynamic render state
///
/// This method renders the stable tree structure and overlays any dynamic
/// elements from RenderState (cursor, selections, animated properties).
///
/// The tree structure is only rebuilt when elements are added/removed.
/// The RenderState is updated every frame for animations and cursor blink.
pub fn render_tree_with_state(
&mut self,
tree: &RenderTree,
render_state: &blinc_layout::RenderState,
target: &wgpu::TextureView,
width: u32,
height: u32,
) -> Result<()> {
self.ctx
.render_tree_with_state(tree, render_state, width, height, target)
}
/// Render a pre-computed render tree with motion animations
///
/// This method renders elements with enter/exit animations applied:
/// - opacity fading
/// - scale transformations
/// - translation animations
///
/// Use this when you have elements wrapped in motion() containers.
pub fn render_tree_with_motion(
&mut self,
tree: &RenderTree,
render_state: &blinc_layout::RenderState,
target: &wgpu::TextureView,
width: u32,
height: u32,
) -> Result<()> {
self.ctx
.render_tree_with_motion(tree, render_state, width, height, target)
}
/// Render an overlay tree on top of existing content (no clear)
///
/// This is used for rendering modal/dialog/toast overlays on top of the main UI.
/// Unlike `render_tree_with_motion`, this method does NOT clear the render target,
/// preserving whatever was rendered before.
pub fn render_overlay_tree_with_motion(
&mut self,
tree: &RenderTree,
render_state: &blinc_layout::RenderState,
target: &wgpu::TextureView,
width: u32,
height: u32,
) -> Result<()> {
self.ctx
.render_overlay_tree_with_motion(tree, render_state, width, height, target)
}
/// Get the render context for advanced usage
pub fn context(&mut self) -> &mut RenderContext {
&mut self.ctx
}
/// Re-run generic font family preloading (sans-serif, monospace)
/// so the family→weight mapping binds to any fonts loaded since
/// the last call. On web, fonts are loaded after `with_canvas`
/// creates the text context, so the initial `preload_generic_styles`
/// runs against an empty registry. This method re-runs the same
/// calls so `.monospace()` / `.serif()` / `.sans_serif()` resolve
/// to the correct loaded font bytes.
pub fn refresh_generic_font_styles(&mut self) {
// Clear cached negative lookups from before fonts were loaded.
// Without this, the first preload attempt (which ran against an
// empty registry in `with_canvas`) caches "not found" for every
// generic family+weight combo, and subsequent preload calls hit
// the cache and return the stale "not found" without retrying.
self.ctx.text_ctx.invalidate_generic_font_cache();
self.ctx.text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[100, 200, 300, 400, 500, 600, 700, 800, 900],
false,
);
self.ctx.text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[100, 200, 300, 400, 500, 600, 700, 800, 900],
true,
);
self.ctx.text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::Monospace,
&[400, 700],
false,
);
}
/// Update the current cursor position in physical pixels (for @flow pointer input)
pub fn set_cursor_position(&mut self, x: f32, y: f32) {
self.ctx.set_cursor_position(x, y);
}
/// Set the current render target texture for blend mode two-pass compositing.
pub fn set_blend_target(&mut self, texture: &wgpu::Texture) {
self.ctx.set_blend_target(texture);
}
/// Clear the blend target texture reference after rendering.
pub fn clear_blend_target(&mut self) {
self.ctx.clear_blend_target();
}
/// Whether the last render frame contained @flow shader elements.
pub fn has_active_flows(&self) -> bool {
self.ctx.has_active_flows()
}
/// Get the configuration
pub fn config(&self) -> &BlincConfig {
&self.config
}
/// Get the wgpu device
pub fn device(&self) -> &Arc<wgpu::Device> {
self.ctx.device()
}
/// Get the wgpu queue
pub fn queue(&self) -> &Arc<wgpu::Queue> {
self.ctx.queue()
}
/// Whether the GPU adapter supports storage buffers.
pub fn has_storage_buffers(&self) -> bool {
self.ctx.has_storage_buffers()
}
/// Create a new wgpu surface for an additional window.
///
/// Uses the existing GPU instance to create a surface that shares
/// the device and queue with the primary renderer. For multi-window support.
pub fn create_surface_for_window<W>(
&self,
window: std::sync::Arc<W>,
) -> std::result::Result<wgpu::Surface<'static>, blinc_gpu::RendererError>
where
W: raw_window_handle::HasWindowHandle
+ raw_window_handle::HasDisplayHandle
+ Send
+ Sync
+ 'static,
{
self.ctx.create_surface(window)
}
/// Get the texture format used by the renderer's pipelines
///
/// This should match the format used for the surface configuration
/// to avoid format mismatches.
pub fn texture_format(&self) -> wgpu::TextureFormat {
self.ctx.texture_format()
}
/// Get the shared font registry
///
/// This can be used to share fonts between text measurement and rendering,
/// ensuring consistent font loading and metrics.
pub fn font_registry(&self) -> Arc<Mutex<FontRegistry>> {
self.ctx.font_registry()
}
/// Load font data into the text rendering registry
///
/// This adds fonts that will be available for text rendering.
/// Returns the number of font faces loaded.
///
/// Use this to load bundled fonts on platforms (like iOS) where
/// system fonts aren't directly accessible via file paths.
pub fn load_font_data_to_registry(&mut self, data: Vec<u8>) -> usize {
self.ctx.load_font_data_to_registry(data)
}
/// Create a new Blinc application with a window surface
///
/// This creates a GPU renderer optimized for the given window and returns
/// both the application and the wgpu surface for rendering.
///
/// # Arguments
///
/// * `window` - The window to create a surface for (must implement raw-window-handle traits)
/// * `config` - Optional configuration (uses defaults if None)
///
/// # Example
///
/// ```ignore
/// let (app, surface) = BlincApp::with_window(window_arc, None)?;
/// ```
#[cfg(feature = "windowed")]
pub fn with_window<W>(
window: Arc<W>,
config: Option<BlincConfig>,
) -> Result<(Self, wgpu::Surface<'static>)>
where
W: raw_window_handle::HasWindowHandle
+ raw_window_handle::HasDisplayHandle
+ Send
+ Sync
+ 'static,
{
let config = config.unwrap_or_default();
let renderer_config = RendererConfig {
max_primitives: config.max_primitives,
max_glass_primitives: config.max_glass_primitives,
max_glyphs: config.max_glyphs,
sample_count: 1,
texture_format: None,
unified_text_rendering: true,
..RendererConfig::default()
};
let (renderer, surface) =
pollster::block_on(GpuRenderer::with_surface(window, renderer_config))
.map_err(|e| BlincError::GpuInit(e.to_string()))?;
let device = renderer.device_arc();
let queue = renderer.queue_arc();
let mut text_ctx = TextRenderingContext::new(device.clone(), queue.clone());
// Load system default font
for font_path in crate::system_font_paths() {
let path = std::path::Path::new(font_path);
if path.exists() {
if let Ok(data) = std::fs::read(path) {
let _ = text_ctx.load_font_data(data);
break;
}
}
}
// Preload common fonts that apps might use
// This ensures fonts are cached before render time
text_ctx.preload_fonts(&[
"Inter",
"Fira Code",
"Menlo",
"SF Mono",
"SF Pro",
"Roboto",
"Consolas",
"Monaco",
"Source Code Pro",
"JetBrains Mono",
]);
// Preload generic font weights (for system fallback fonts)
text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[400, 600, 700, 800, 900],
false,
);
text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[400, 600, 700, 800, 900],
true,
);
text_ctx.preload_generic_styles(blinc_gpu::GenericFont::Monospace, &[400, 700], false);
let ctx = RenderContext::new(renderer, text_ctx, device, queue, config.sample_count);
let app = Self { ctx, config };
Ok((app, surface))
}
/// Async sibling of [`Self::with_window`] for the web target.
///
/// `with_window` blocks on `pollster::block_on(GpuRenderer::with_surface(...))`,
/// which cannot run on the browser main thread — wasm-bindgen-futures
/// requires the entire async chain to be `await`ed back into the JS
/// event loop. This sibling preserves the same shape but is `async`
/// the whole way through, calling [`GpuRenderer::with_canvas`] from
/// `blinc_gpu` instead of `with_surface`.
///
/// **No system-font loading.** On the web there's no filesystem to
/// scan for `.ttf` paths. Apps must call
/// [`Self::load_font_data_to_registry`] explicitly with bundled or
/// fetched font bytes after `with_canvas` returns. The Phase 6
/// rollout adds an async preload helper in `blinc_platform_web`.
#[cfg(all(feature = "web", target_arch = "wasm32"))]
pub async fn with_canvas(
canvas: web_sys::HtmlCanvasElement,
config: Option<BlincConfig>,
) -> Result<(Self, wgpu::Surface<'static>)> {
let config = config.unwrap_or_default();
let renderer_config = RendererConfig {
max_primitives: config.max_primitives,
max_glass_primitives: config.max_glass_primitives,
max_glyphs: config.max_glyphs,
sample_count: 1,
texture_format: None,
unified_text_rendering: true,
..RendererConfig::default()
};
let (renderer, surface) = GpuRenderer::with_canvas(canvas, renderer_config)
.await
.map_err(|e| BlincError::GpuInit(e.to_string()))?;
let device = renderer.device_arc();
let queue = renderer.queue_arc();
let mut text_ctx = TextRenderingContext::new(device.clone(), queue.clone());
// Generic-font preload mirrors the desktop path so common
// weights are cached before the first frame. The actual font
// bytes have to be supplied separately by the caller via
// `load_font_data()` — these calls only register the
// generic-family → weight mappings so the shaper knows
// which families to resolve `font-family: sans-serif` /
// `monospace` to. Without them, CSS `font-family: monospace`
// falls back to the first registered font (usually Arial)
// instead of the intended monospace font.
text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[100, 200, 300, 400, 500, 600, 700, 800, 900],
false,
);
text_ctx.preload_generic_styles(
blinc_gpu::GenericFont::SansSerif,
&[100, 200, 300, 400, 500, 600, 700, 800, 900],
true,
);
text_ctx.preload_generic_styles(blinc_gpu::GenericFont::Monospace, &[400, 700], false);
let ctx = RenderContext::new(renderer, text_ctx, device, queue, config.sample_count);
let app = Self { ctx, config };
Ok((app, surface))
}
}