whisker-engine 0.15.0

Host-independent retained scene and frame production for Whisker.
Documentation
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Rust-facing Host measurement boundary and layout driver.

use std::{error::Error, fmt};

use whisker_layout::LayoutSize;
use whisker_protocol::{
    MeasurementBatchError, MeasurementRequest, MeasurementResponse, NodeId, SurfaceId,
    validate_measurement_batch,
};

use crate::{LayoutProgress, SurfaceEngine, SurfaceError};

/// Host capability required to resolve one batch of intrinsic measurements.
///
/// Android, UIKit, DOM, and native Desktop bindings implement this information flow at
/// their generated boundary. The trait itself contains no platform types and
/// is also the conformance seam used by Rust-only tests.
pub trait MeasurementProvider {
    /// Backend or binding failure returned before a batch can be accepted.
    type Error;

    /// Measures every request and appends exactly one correlated response for each.
    ///
    /// The output vector is empty on entry. Returning `Ok` commits no state by
    /// itself: Rust validates the complete response set transactionally before
    /// applying any result.
    fn measure_batch(
        &mut self,
        surface: SurfaceId,
        requests: &[MeasurementRequest],
        responses: &mut Vec<MeasurementResponse>,
    ) -> Result<(), Self::Error>;
    /// Retains measurement-cache objects independently of the currently displayed frame.
    fn retain_prepared_content(
        &mut self,
        _surface: SurfaceId,
        _revision: u64,
        _retained: &mut dyn Iterator<Item = whisker_protocol::PreparedContentId>,
    ) {
    }
}

/// Limit for synchronous Host batches attempted by one layout drive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayoutOptions {
    /// Maximum number of immediate request/response rounds.
    pub max_immediate_batches: usize,
}

impl Default for LayoutOptions {
    fn default() -> Self {
        Self {
            max_immediate_batches: 32,
        }
    }
}

/// Failure while driving Taffy through the Rust-to-Host measurement boundary.
#[derive(Clone, Debug, PartialEq)]
pub enum LayoutError<MeasurementError> {
    /// Retained surface or response semantics were invalid.
    Surface(SurfaceError),
    /// The Host binding failed without producing an accepted batch.
    Measurement(MeasurementError),
    /// The Host returned a structurally malformed response set.
    InvalidBatch(MeasurementBatchError),
    /// Immediate measurements did not converge within the configured guard.
    BatchLimitExceeded {
        /// Configured maximum number of Host calls.
        limit: usize,
    },
}

impl<MeasurementError: fmt::Debug> fmt::Display for LayoutError<MeasurementError> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "Whisker Host layout error: {self:?}")
    }
}

impl<MeasurementError: Error + 'static> Error for LayoutError<MeasurementError> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Surface(error) => Some(error),
            Self::Measurement(error) => Some(error),
            Self::InvalidBatch(_) | Self::BatchLimitExceeded { .. } => None,
        }
    }
}

impl<MeasurementError> From<SurfaceError> for LayoutError<MeasurementError> {
    fn from(error: SurfaceError) -> Self {
        Self::Surface(error)
    }
}

impl SurfaceEngine {
    /// Runs layout and all immediately answerable Host measurement batches.
    ///
    /// A synchronous Text provider normally makes this return
    /// [`LayoutProgress::Complete`] in one call. If a provider returns
    /// `Pending`, this returns blocked or provisional progress; a later
    /// Host-to-Rust [`MeasurementReady`](whisker_protocol::MeasurementReady)
    /// event is applied with [`SurfaceEngine::apply_measurement_ready`] before
    /// driving layout again.
    pub fn drive_layout<Provider: MeasurementProvider>(
        &mut self,
        root: NodeId,
        viewport: LayoutSize,
        environment_epoch: u64,
        provider: &mut Provider,
        options: LayoutOptions,
    ) -> Result<LayoutProgress, LayoutError<Provider::Error>> {
        let mut batches = 0;
        loop {
            let progress =
                self.compute_layout_with_measurements(root, viewport, environment_epoch)?;
            if progress.requests().is_empty() {
                self.synchronize_prepared_content(provider);
                return Ok(progress);
            }
            if batches >= options.max_immediate_batches {
                return Err(LayoutError::BatchLimitExceeded {
                    limit: options.max_immediate_batches,
                });
            }

            let requests = progress.requests().to_vec();
            let mut responses = Vec::with_capacity(requests.len());
            provider
                .measure_batch(self.surface(), &requests, &mut responses)
                .map_err(LayoutError::Measurement)?;
            validate_measurement_batch(&requests, &responses).map_err(LayoutError::InvalidBatch)?;
            self.apply_measurement_responses(&responses)?;
            batches += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use whisker_protocol::{
        ApplyResult, ElementTypeId, MeasureFontFamily, MeasureFontStyle, MeasureLineHeight,
        MeasureTextDirection, MeasureTextOverflow, MeasureTextWrap, MeasuredSize,
        MeasurementMetrics, MeasurementPayload, MeasurementPayloadError, MeasurementRequestId,
        MeasurementSpec, Operation, PendingMeasurePolicy, PreparedContentId,
        ReplacedContentMeasurePayload, TextMeasurePayload, TextMeasureStyle,
    };
    use whisker_style::{ComputedLayoutStyle, SpecifiedStyle, StyleEnvironment, resolve_style};

    use super::*;
    use crate::{FrameSink, PlainTextInput, RecordingRenderer, SceneError};

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum TestHostError {
        Failed,
    }

    impl fmt::Display for TestHostError {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("test Host failed")
        }
    }

    impl Error for TestHostError {}

    #[derive(Clone, Copy)]
    enum Reply {
        Ready(MeasuredSize),
        ReadyPreparedText,
        InvalidMetrics,
        Pending,
        Missing,
        Fail,
    }

    struct TestHost {
        reply: Reply,
        calls: Vec<(SurfaceId, Vec<MeasurementRequest>)>,
    }

    impl TestHost {
        fn new(reply: Reply) -> Self {
            Self {
                reply,
                calls: Vec::new(),
            }
        }
    }

    impl MeasurementProvider for TestHost {
        type Error = TestHostError;

        fn measure_batch(
            &mut self,
            surface: SurfaceId,
            requests: &[MeasurementRequest],
            responses: &mut Vec<MeasurementResponse>,
        ) -> Result<(), Self::Error> {
            assert!(responses.is_empty());
            self.calls.push((surface, requests.to_vec()));
            match self.reply {
                Reply::Ready(size) => {
                    responses.extend(requests.iter().map(|request| MeasurementResponse::Ready {
                        key: request.key,
                        environment_epoch: request.environment_epoch,
                        metrics: MeasurementMetrics::from_size(size),
                    }))
                }
                Reply::ReadyPreparedText => responses.extend(requests.iter().map(|request| {
                    let MeasurementPayload::Text(payload) = &request.payload else {
                        panic!("plain-text Host received a non-text request");
                    };
                    let width = payload.text.chars().count() as f32 * 9.0;
                    MeasurementResponse::Ready {
                        key: request.key,
                        environment_epoch: request.environment_epoch,
                        metrics: MeasurementMetrics {
                            paragraph: None,
                            inline_placements: Vec::new(),
                            size: MeasuredSize::new(width, 21.0),
                            first_baseline: Some(15.0),
                            last_baseline: Some(15.0),
                            overflow: None,
                            prepared_content: Some(
                                PreparedContentId::new(request.key.get())
                                    .expect("measurement keys are non-zero"),
                            ),
                        },
                    }
                })),
                Reply::InvalidMetrics => {
                    responses.extend(requests.iter().map(|request| MeasurementResponse::Ready {
                        key: request.key,
                        environment_epoch: request.environment_epoch,
                        metrics: MeasurementMetrics::from_size(MeasuredSize::new(-1.0, 0.0)),
                    }))
                }
                Reply::Pending => responses.extend(requests.iter().map(|request| {
                    MeasurementResponse::Pending {
                        key: request.key,
                        environment_epoch: request.environment_epoch,
                        request_id: MeasurementRequestId::new(request.key.get())
                            .expect("non-zero request key"),
                        provisional: None,
                    }
                })),
                Reply::Missing => {}
                Reply::Fail => return Err(TestHostError::Failed),
            }
            Ok(())
        }
    }

    fn id<T>(constructor: impl FnOnce(u64) -> Option<T>) -> T {
        constructor(1).expect("non-zero test id")
    }

    fn text_spec() -> MeasurementSpec {
        MeasurementSpec {
            content_hash: 1,
            style_hash: 2,
            payload: MeasurementPayload::Text(TextMeasurePayload {
                runs: Vec::new(),
                attachments: Vec::new(),
                text: "measure me".into(),
                style: TextMeasureStyle {
                    font_families: vec![MeasureFontFamily::Named("Inter".into())],
                    font_size: 16.0,
                    font_weight: 500,
                    font_style: MeasureFontStyle::Normal,
                    line_height: MeasureLineHeight::LogicalPixels(20.0),
                    letter_spacing: 0.5,
                    ..TextMeasureStyle::default()
                },
                locale: Some("en-US".into()),
                direction: MeasureTextDirection::LeftToRight,
                alignment: whisker_protocol::MeasureTextAlignment::Start,
                indent: Default::default(),
                wrap: MeasureTextWrap::Wrap,
                word_break: Default::default(),
                max_lines: Some(2),
                overflow: MeasureTextOverflow::Ellipsis,
            }),
            pending_policy: PendingMeasurePolicy::Block,
        }
    }

    fn surface_with_text() -> (SurfaceEngine, NodeId) {
        let mut surface = SurfaceEngine::new(id(SurfaceId::new));
        let root = surface
            .create_node(
                ElementTypeId::new(1).expect("non-zero element type"),
                ComputedLayoutStyle::default(),
            )
            .expect("create text node");
        surface
            .set_measurement(root, Some(text_spec()))
            .expect("register text measurement");
        (surface, root)
    }

    #[test]
    fn synchronous_host_completes_text_layout_before_returning() {
        let (mut surface, root) = surface_with_text();
        let mut host = TestHost::new(Reply::Ready(MeasuredSize::new(48.0, 20.0)));
        let progress = surface
            .drive_layout(
                root,
                LayoutSize::new(100.0, 100.0),
                7,
                &mut host,
                LayoutOptions::default(),
            )
            .expect("synchronous layout");

        assert!(progress.has_layout());
        assert!(progress.requests().is_empty());
        assert!(!host.calls.is_empty());
        assert!(host.calls.iter().all(|(id, requests)| {
            *id == surface.surface()
                && requests.iter().all(|request| {
                    request.payload.kind() == whisker_protocol::MeasurementKind::Text
                })
        }));
        assert_eq!(
            surface.last_measurement(root).map(|metrics| metrics.size),
            Some(MeasuredSize::new(48.0, 20.0))
        );
    }

    #[test]
    fn plain_text_reaches_final_snapshot_and_incremental_frame_with_mock_host() {
        let resolved = resolve_style(&SpecifiedStyle::new(), None, StyleEnvironment::default())
            .expect("default computed style");
        let mut surface = SurfaceEngine::new(id(SurfaceId::new));
        let root = surface
            .create_node(
                ElementTypeId::new(1).expect("text element type"),
                resolved.computed().layout().clone(),
            )
            .expect("create text node");
        let first_input = PlainTextInput::new("hello");
        let missing = NodeId::new(99).expect("missing node");
        assert_eq!(
            surface.set_plain_text(missing, &first_input, resolved.computed(),),
            Err(SurfaceError::Scene(SceneError::UnknownNode {
                node: missing
            }))
        );
        let mut invalid = first_input.clone();
        invalid.locale = Some(String::new());
        assert_eq!(
            surface.set_plain_text(root, &invalid, resolved.computed()),
            Err(SurfaceError::Measurement(
                crate::MeasurementError::InvalidPayload {
                    node: root,
                    error: MeasurementPayloadError::InvalidLocale,
                }
            ))
        );
        assert!(
            surface
                .set_plain_text(root, &first_input, resolved.computed())
                .expect("lower first text")
        );
        assert!(
            !surface
                .set_plain_text(root, &first_input, resolved.computed())
                .expect("equal unmeasured text is idle")
        );

        let mut host = TestHost::new(Reply::ReadyPreparedText);
        let progress = surface
            .drive_layout(
                root,
                LayoutSize::new(200.0, 100.0),
                3,
                &mut host,
                LayoutOptions::default(),
            )
            .expect("measure and finalize first text layout");
        assert!(progress.has_layout());
        let first_measure_batches = host.calls.len();
        assert!(first_measure_batches > 0);
        let first_prepared = surface
            .last_measurement(root)
            .and_then(|metrics| metrics.prepared_content)
            .expect("final text measurement keeps prepared content");

        let first_packet = surface
            .prepare_frame(3)
            .expect("prepare snapshot")
            .expect("snapshot has text work")
            .clone();
        assert_eq!(
            surface.set_plain_text(root, &first_input, resolved.computed()),
            Err(SurfaceError::Scene(SceneError::FramePending))
        );
        assert!(matches!(
            first_packet
                .operations
                .iter()
                .find(|operation| matches!(operation, Operation::SetLayout { .. })),
            Some(Operation::SetLayout { node, geometry })
                if *node == root && geometry.border_box == whisker_protocol::LayoutRect {
                    x: 0.0,
                    y: 0.0,
                    width: 200.0,
                    height: 21.0,
                }
        ));
        assert!(matches!(
            first_packet
                .operations
                .iter()
                .find(|operation| matches!(operation, Operation::SetText { .. })),
            Some(Operation::SetText { node, content })
                if *node == root
                    && content.payload.text == "hello"
                    && content.prepared_content == Some(first_prepared)
        ));

        let mut renderer = RecordingRenderer::new(surface.surface());
        assert_eq!(
            renderer.present(&first_packet),
            Ok(ApplyResult::Accepted { revision: 1 })
        );
        surface.accept_pending(1).expect("accept snapshot");
        assert_eq!(renderer.projection().node_count(), 1);

        let second_input = PlainTextInput::new("hello world");
        assert!(
            surface
                .set_plain_text(root, &second_input, resolved.computed())
                .expect("lower changed text")
        );
        surface
            .drive_layout(
                root,
                LayoutSize::new(200.0, 100.0),
                3,
                &mut host,
                LayoutOptions::default(),
            )
            .expect("measure and finalize changed text layout");
        let second_measure_batches = host.calls.len();
        assert!(second_measure_batches > first_measure_batches);
        let second_prepared = surface
            .last_measurement(root)
            .and_then(|metrics| metrics.prepared_content)
            .expect("changed text keeps prepared content");
        let delta = surface
            .prepare_frame(3)
            .expect("prepare delta")
            .expect("changed text has work")
            .clone();
        assert!(matches!(
            delta.operations.as_slice(),
            [Operation::SetText { node: text_node, content }]
                if *text_node == root
                    && content.payload.text == "hello world"
                    && content.prepared_content == Some(second_prepared)
        ));
        assert_eq!(
            renderer.present(&delta),
            Ok(ApplyResult::Accepted { revision: 2 })
        );
        surface.accept_pending(2).expect("accept delta");

        assert!(
            !surface
                .set_plain_text(root, &second_input, resolved.computed())
                .expect("equal text is idle")
        );
        surface
            .drive_layout(
                root,
                LayoutSize::new(200.0, 100.0),
                3,
                &mut host,
                LayoutOptions::default(),
            )
            .expect("equal text reuses retained layout");
        assert_eq!(host.calls.len(), second_measure_batches);
        assert_eq!(surface.prepare_frame(3).expect("idle prepare"), None);
    }

    #[test]
    #[should_panic(expected = "plain-text Host received a non-text request")]
    fn plain_text_test_host_rejects_non_text_requests() {
        let mut surface = SurfaceEngine::new(id(SurfaceId::new));
        let root = surface
            .create_node(
                ElementTypeId::new(1).expect("element type"),
                ComputedLayoutStyle::default(),
            )
            .expect("create node");
        surface
            .set_measurement(
                root,
                Some(MeasurementSpec {
                    content_hash: 1,
                    style_hash: 1,
                    payload: MeasurementPayload::ReplacedContent(
                        ReplacedContentMeasurePayload::default(),
                    ),
                    pending_policy: PendingMeasurePolicy::Block,
                }),
            )
            .expect("register replaced measurement");
        let mut host = TestHost::new(Reply::ReadyPreparedText);
        let _ = surface.drive_layout(
            root,
            LayoutSize::new(100.0, 100.0),
            1,
            &mut host,
            LayoutOptions::default(),
        );
    }

    #[test]
    fn pending_host_returns_control_to_the_event_boundary() {
        let (mut surface, root) = surface_with_text();
        let mut host = TestHost::new(Reply::Pending);
        let progress = surface
            .drive_layout(
                root,
                LayoutSize::new(100.0, 100.0),
                1,
                &mut host,
                LayoutOptions::default(),
            )
            .expect("pending layout is valid");
        assert_eq!(host.calls.len(), 1);
        assert!(matches!(
            progress,
            LayoutProgress::Blocked { requests, pending }
                if requests.is_empty() && pending == host.calls[0].1.len()
        ));
    }

    #[test]
    fn host_and_batch_failures_are_transactional_and_diagnostic() {
        let (mut surface, root) = surface_with_text();
        let mut failed = TestHost::new(Reply::Fail);
        let error = surface
            .drive_layout(
                root,
                LayoutSize::new(100.0, 100.0),
                1,
                &mut failed,
                LayoutOptions::default(),
            )
            .expect_err("Host failure");
        assert_eq!(error, LayoutError::Measurement(TestHostError::Failed));
        assert!(error.source().is_some());
        assert!(error.to_string().contains("Host"));
        assert_eq!(TestHostError::Failed.to_string(), "test Host failed");

        let mut missing = TestHost::new(Reply::Missing);
        let error = surface
            .drive_layout(
                root,
                LayoutSize::new(100.0, 100.0),
                1,
                &mut missing,
                LayoutOptions::default(),
            )
            .expect_err("missing response");
        assert_eq!(
            error,
            LayoutError::InvalidBatch(MeasurementBatchError::MissingResponseKey {
                key: whisker_protocol::MeasurementKey::new(1).expect("first request key"),
            })
        );
        assert!(error.source().is_none());

        let mut invalid_metrics = TestHost::new(Reply::InvalidMetrics);
        let error = surface
            .drive_layout(
                root,
                LayoutSize::new(100.0, 100.0),
                1,
                &mut invalid_metrics,
                LayoutOptions::default(),
            )
            .expect_err("invalid metrics");
        assert_eq!(
            error,
            LayoutError::Surface(SurfaceError::Measurement(
                crate::MeasurementError::InvalidMetrics {
                    key: whisker_protocol::MeasurementKey::new(1).expect("first request key"),
                }
            ))
        );
    }

    #[test]
    fn surface_failure_and_batch_limit_do_not_call_host() {
        let mut empty = SurfaceEngine::new(id(SurfaceId::new));
        let mut host = TestHost::new(Reply::Ready(MeasuredSize::default()));
        let error = empty
            .drive_layout(
                id(NodeId::new),
                LayoutSize::new(1.0, 1.0),
                1,
                &mut host,
                LayoutOptions::default(),
            )
            .expect_err("unknown root");
        assert_eq!(
            error,
            LayoutError::Surface(SurfaceError::Layout(
                whisker_layout::LayoutError::UnknownNode(id(NodeId::new))
            ))
        );
        assert!(error.source().is_some());

        let (mut surface, root) = surface_with_text();
        let error = surface
            .drive_layout(
                root,
                LayoutSize::new(100.0, 100.0),
                1,
                &mut host,
                LayoutOptions {
                    max_immediate_batches: 0,
                },
            )
            .expect_err("zero batch guard");
        assert_eq!(error, LayoutError::BatchLimitExceeded { limit: 0 });
        assert!(error.source().is_none());
        assert!(host.calls.is_empty());
    }
}