waft-widgets 0.15.0

Widget framework and widgets for Waft
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
//! A camera running for an app, as the app holds it, and the view that shows its preview.

use std::fmt;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use waft_embedder::{
    Camera, CameraDevice, CameraError, CameraFormat, CameraListFuture, CameraOpenFuture,
    CameraOutputs, CaptureSession, CaptureState, CompositionLayer, MediaChangeFuture, PhotoFuture,
    RecordingFuture, Size,
};
use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Ref, Task};

use super::at_size;
use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
use crate::widgets::basic::SizedBox;
use crate::widgets::composition_layer_view::CompositionLayerView;
use crate::widgets::transitions::ListenableBuilder;

/// The cameras attached now, in the system's order; none where the platform has no cameras:
/// Flutter's `availableCameras`. Listing asks the user nothing.
pub fn available_cameras(app: &App) -> CameraListFuture {
    match app.platform().cameras() {
        Some(cameras) => cameras.cameras(),
        None => Box::pin(std::future::ready(Vec::new())),
    }
}

/// Resolves once [`available_cameras`] may answer something else than when this was called: a
/// camera plugged in or out; `None` where the platform has no cameras.
pub fn available_cameras_changed(app: &App) -> Option<MediaChangeFuture> {
    Some(app.platform().cameras()?.changed())
}

/// Opens `camera`, asking the user for the cameras first where the system asks and the user has
/// not answered; `None` where the platform has no cameras. The camera opened lists the formats it
/// runs in, and a [`CameraSession`] starts it in one.
pub fn open_camera(app: &App, camera: &Camera) -> Option<CameraOpenFuture> {
    Some(app.platform().cameras()?.open(camera))
}

/// A camera running for the app in one format, feeding the outputs it started with, each the
/// system's own: the host's session, whose listeners hear its state change.
pub struct CameraSession {
    change_notifier: ChangeNotifierData,
    /// The host's session, until [`dispose`](CameraSession::dispose).
    host: Option<Rc<dyn CaptureSession>>,
    /// The format the camera runs in for the session.
    format: CameraFormat,
    /// The host's state when it last changed.
    state: CaptureState,
    /// The host's rotation angles, the preview's and the capture's, when they last changed.
    rotation_angles: [u32; 2],
    /// The layer the preview shows on, among the outputs it started with, which a
    /// [`CameraPreview`] places.
    preview_layer: Option<Arc<dyn CompositionLayer>>,
}

impl CameraSession {
    /// Starts `camera` in `format`, one of its formats, feeding `outputs`, which the system
    /// configures together, and answers the session once it runs, or is interrupted, from which
    /// it resumes by itself; where the camera already runs for another session in a format of its
    /// own, the session joins that one, which [`format`](CameraSession::format) says. It fails
    /// for what can happen at any time: the camera in use, unplugged, or not allowed; and for a
    /// format the camera does not list.
    pub fn start(
        app: &App,
        camera: &dyn CameraDevice,
        format: &CameraFormat,
        outputs: CameraOutputs,
    ) -> Task<Result<Ref<CameraSession>, CameraError>> {
        let preview_layer = outputs.preview.clone();
        let starting = camera.start(format, outputs);
        app.spawn(async move |cx| {
            let host = starting.await?;
            Ok(cx.update(|app| CameraSession::of_host(app, Rc::from(host), preview_layer)))
        })
    }

    /// The session over `host`, which started with its preview on `preview_layer`, following its
    /// state from now on.
    fn of_host(
        app: &mut App,
        host: Rc<dyn CaptureSession>,
        preview_layer: Option<Arc<dyn CompositionLayer>>,
    ) -> Ref<CameraSession> {
        let changed = host.changed();
        let session = app.create(CameraSession {
            change_notifier: ChangeNotifierData::new(),
            format: host.format(),
            state: host.state(),
            rotation_angles: rotation_angles_of(&*host),
            host: Some(host),
            preview_layer,
        });
        session.follow(app, changed);
        session
    }

    /// The format the camera runs in: the one picked, unless the session joined another.
    pub fn format(self: Handle<Self>, app: &App) -> &CameraFormat {
        &app.get(self).format
    }

    /// The session's state when it last changed.
    pub fn state(self: Handle<Self>, app: &App) -> &CaptureState {
        &app.get(self).state
    }

    /// The turn, in degrees clockwise, that keeps the preview level, when it last changed:
    /// [`CaptureSession::video_rotation_angle_for_horizon_level_preview`]. The system's preview is
    /// turned so on its layer, which a [`CameraPreview`] lays out turned.
    pub fn video_rotation_angle_for_horizon_level_preview(self: Handle<Self>, app: &App) -> u32 {
        app.get(self).rotation_angles[0]
    }

    /// The turn that keeps what is captured level, when it last changed:
    /// [`CaptureSession::video_rotation_angle_for_horizon_level_capture`].
    pub fn video_rotation_angle_for_horizon_level_capture(self: Handle<Self>, app: &App) -> u32 {
        app.get(self).rotation_angles[1]
    }

    /// The layer the preview shows on, which a [`CameraPreview`] places; `None` where the session
    /// started without one, or once disposed.
    pub fn preview_layer(self: Handle<Self>, app: &App) -> Option<&Arc<dyn CompositionLayer>> {
        app.get(self).preview_layer.as_ref()
    }

    /// Takes a photo, captured, processed and encoded by the system, while the session runs with
    /// photos among its outputs.
    pub fn take_photo(self: Handle<Self>, app: &App) -> PhotoFuture {
        self.host(app).take_photo()
    }

    /// Records to a new file at `path`, encoded and written by the system, while the session runs
    /// with movies among its outputs, until [`stop_recording`](CameraSession::stop_recording).
    pub fn start_recording(self: Handle<Self>, app: &App, path: PathBuf) -> RecordingFuture {
        self.host(app).start_recording(path)
    }

    /// Ends the recording, whose future then answers.
    pub fn stop_recording(self: Handle<Self>, app: &App) {
        self.host(app).stop_recording();
    }

    /// Stops the camera for the app and lets go of the host's session: its preview leaves the
    /// layer it was on, and its listeners hear nothing more.
    pub fn dispose(self: Handle<Self>, app: &mut App) {
        let session = app.get_mut(self);
        session.host = None;
        session.preview_layer = None;
        ChangeNotifierData::dispose(app, self);
    }

    /// The host's session.
    ///
    /// # Panics
    ///
    /// Once disposed.
    fn host(self: Handle<Self>, app: &App) -> &dyn CaptureSession {
        app.get(self)
            .host
            .as_deref()
            .expect("a CameraSession used after dispose")
    }

    /// Takes the host's state at each of its changes, from the one `changed` resolves at, until
    /// the session is disposed or no longer kept.
    fn follow(self: Handle<Self>, app: &mut App, changed: MediaChangeFuture) {
        let _following = app.spawn(async move |cx| {
            let mut changed = changed;
            loop {
                changed.await;
                let next = cx.update(|app| {
                    let session = self.upgrade(app)?;
                    session.take_host_state(app)
                });
                match next {
                    Some(next) => changed = next,
                    None => return,
                }
            }
        });
    }

    /// Takes the host's state and rotation angles, telling the listeners if either changed;
    /// answers the future of the host's next change, asked before they are read so that no change
    /// goes unheard, or `None` once the session is disposed.
    fn take_host_state(self: Handle<Self>, app: &mut App) -> Option<MediaChangeFuture> {
        let host = app.get(self).host.clone()?;
        let next = host.changed();
        let state = host.state();
        let rotation_angles = rotation_angles_of(&*host);
        let session = app.get_mut(self);
        if state != session.state || rotation_angles != session.rotation_angles {
            session.state = state;
            session.rotation_angles = rotation_angles;
            self.notify_listeners(app);
        }
        Some(next)
    }
}

/// `host`'s rotation angles, the preview's and the capture's.
fn rotation_angles_of(host: &dyn CaptureSession) -> [u32; 2] {
    [
        host.video_rotation_angle_for_horizon_level_preview(),
        host.video_rotation_angle_for_horizon_level_capture(),
    ]
}

impl ChangeNotifier for CameraSession {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

impl fmt::Debug for CameraSession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CameraSession")
            .field("format", &self.format)
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

/// A camera session's preview, laid out at the size of the format the camera runs in, turned by
/// the preview's rotation angle, in logical pixels, or as large as the constraints let it be at
/// that aspect; laid out again as the angle changes. It places the layer the
/// session started with for its preview, which the system draws into; a session started without
/// one shows nothing there.
#[derive(Clone)]
pub struct CameraPreview {
    pub key: Option<KeyRef>,
    pub session: Ref<CameraSession>,
}

impl CameraPreview {
    pub fn new(session: Ref<CameraSession>) -> CameraPreview {
        CameraPreview { key: None, session }
    }

    pub fn key(mut self, key: KeyRef) -> CameraPreview {
        self.key = Some(key);
        self
    }
}

impl fmt::Debug for CameraPreview {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CameraPreview").finish_non_exhaustive()
    }
}

impl StatelessWidget for CameraPreview {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        let session = self.session.clone();
        ListenableBuilder::new(Rc::new(session.clone()), move |app, _context, _child| {
            let size = turned(
                session.format(app).size,
                session.video_rotation_angle_for_horizon_level_preview(app),
            );
            let preview = match session.preview_layer(app) {
                Some(layer) => CompositionLayerView::new(Arc::clone(layer)).into_widget(),
                None => SizedBox::expand().into_widget(),
            };
            at_size(size, preview)
        })
        .into_widget()
    }
}

/// `size` turned `angle` degrees clockwise: its sides swapped by a quarter turn.
fn turned(size: Size, angle: u32) -> Size {
    if angle % 180 == 90 {
        Size::new(size.height(), size.width())
    } else {
        size
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;
    use waft_foundation::Ref;

    use waft_embedder::{
        CameraFacing, CameraId, CameraInterruption, MediaError, MovieOptions, Photo, Size,
        TargetPlatform, VideoFrameReaders,
    };
    use waft_foundation::{AppCell, ListenableObject, Listener};
    use waft_test::{MockCameras, MockCompositor, MockVideoFrameReaders, TestPlatform, TestView};

    use super::*;
    use crate::testing::WidgetTester;

    fn front_camera() -> Camera {
        Camera {
            id: CameraId("front".to_owned()),
            name: "Front camera".to_owned(),
            facing: CameraFacing::Front,
        }
    }

    fn format(width: f64, height: f64) -> CameraFormat {
        CameraFormat {
            size: Size::new(width, height),
            min_frame_rate: 15.0,
            max_frame_rate: 30.0,
            photo_sizes: vec![Size::new(width, height)],
        }
    }

    fn cameras() -> MockCameras {
        MockCameras::new(vec![front_camera()])
            .with_formats(vec![format(1920.0, 1080.0), format(640.0, 480.0)])
    }

    fn app_with(cameras: &MockCameras, compositor: &MockCompositor) -> Rc<AppCell> {
        let platform = platform_with(cameras, compositor)
            .with_view(Rc::new(TestView::new(400.0, 800.0)) as waft_embedder::ViewRef);
        AppCell::with_platform(Rc::new(platform))
    }

    /// An iPhone with `cameras`, compositing through `compositor`.
    fn platform_with(cameras: &MockCameras, compositor: &MockCompositor) -> TestPlatform {
        TestPlatform::new()
            .on(TargetPlatform::IOS)
            .with_cameras(Rc::new(cameras.clone()))
            .with_compositor(Arc::new(compositor.clone()))
    }

    /// Runs `future` to its end, which the mocks answer without waiting.
    fn now<T>(future: impl std::future::Future<Output = T>) -> T {
        let mut future = std::pin::pin!(future);
        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
        match future.as_mut().poll(&mut context) {
            std::task::Poll::Ready(output) => output,
            std::task::Poll::Pending => panic!("the mock answers at once"),
        }
    }

    /// Starts `camera` as an app does, running the app's tasks until the start answers.
    fn start(
        cell: &AppCell,
        camera: &dyn CameraDevice,
        format: &CameraFormat,
        outputs: CameraOutputs,
    ) -> Result<Ref<CameraSession>, CameraError> {
        let starting = CameraSession::start(&cell.borrow(), camera, format, outputs);
        cell.checkpoint();
        now(starting)
    }

    fn opened(cell: &AppCell) -> Box<dyn CameraDevice> {
        let opening =
            open_camera(&cell.borrow(), &front_camera()).expect("a platform with cameras");
        now(opening).expect("the user lets the app use the cameras")
    }

    #[test]
    fn the_cameras_are_the_platforms_and_none_where_it_has_none() {
        let cameras = cameras();
        let cell = app_with(&cameras, &MockCompositor::new());
        assert_eq!(now(available_cameras(&cell.borrow())), vec![front_camera()]);

        let without = AppCell::with_platform(Rc::new(TestPlatform::new()));
        assert!(now(available_cameras(&without.borrow())).is_empty());
        assert!(available_cameras_changed(&without.borrow()).is_none());
        assert!(open_camera(&without.borrow(), &front_camera()).is_none());
    }

    #[test]
    fn the_cameras_change_as_one_comes_or_goes() {
        let cameras = cameras();
        let cell = app_with(&cameras, &MockCompositor::new());
        let mut changed =
            available_cameras_changed(&cell.borrow()).expect("a platform with cameras");
        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(changed.as_mut().poll(&mut context).is_pending());

        let plugged_in = Camera {
            id: CameraId("usb".to_owned()),
            name: "USB camera".to_owned(),
            facing: CameraFacing::External,
        };
        cameras.set_cameras(vec![front_camera(), plugged_in.clone()]);
        assert!(changed.as_mut().poll(&mut context).is_ready());
        assert_eq!(
            now(available_cameras(&cell.borrow())),
            vec![front_camera(), plugged_in]
        );

        let mut changed = available_cameras_changed(&cell.borrow()).unwrap();
        assert!(
            changed.as_mut().poll(&mut context).is_pending(),
            "a change before the future was asked for is not one after it"
        );
        cameras.set_cameras(vec![front_camera()]);
        assert!(changed.as_mut().poll(&mut context).is_ready());
        assert_eq!(now(available_cameras(&cell.borrow())), vec![front_camera()]);
    }

    #[test]
    fn a_camera_the_user_does_not_allow_does_not_open() {
        let cell = app_with(&cameras().denying(), &MockCompositor::new());
        let opening = open_camera(&cell.borrow(), &front_camera()).unwrap();
        assert!(matches!(now(opening), Err(CameraError::NotAllowed)));
    }

    #[test]
    fn a_camera_starts_in_a_format_it_lists_with_its_outputs_given_whole() {
        let cameras = cameras();
        let cell = app_with(&cameras, &MockCompositor::new());
        let camera = opened(&cell);
        let formats = camera.formats();
        assert_eq!(formats, vec![format(1920.0, 1080.0), format(640.0, 480.0)]);

        let reader = MockVideoFrameReaders::new().make_reader();
        let outputs = CameraOutputs::new()
            .frames(Arc::clone(&reader))
            .photos(Size::new(640.0, 480.0))
            .movies(MovieOptions { sound: true });
        let session = start(&cell, &*camera, &formats[1], outputs).unwrap();
        let host = &cameras.sessions()[0];
        assert_eq!(host.camera(), front_camera());
        assert_eq!(*session.format(&cell.borrow()), format(640.0, 480.0));
        assert!(Arc::ptr_eq(&host.frame_reader().unwrap(), &reader));
        assert_eq!(host.photo_size(), Some(Size::new(640.0, 480.0)));
        assert_eq!(host.movie_options(), Some(MovieOptions { sound: true }));
        assert_eq!(*session.state(&cell.borrow()), CaptureState::Running);

        let unlisted = format(320.0, 240.0);
        assert!(matches!(
            start(&cell, &*camera, &unlisted, CameraOutputs::new()),
            Err(CameraError::Failed(_))
        ));

        session.dispose(&mut cell.borrow_mut());
        assert!(host.is_dropped());
    }

    #[test]
    fn a_session_on_a_camera_another_runs_joins_its_format_and_says_so() {
        let cameras = cameras();
        let cell = app_with(&cameras, &MockCompositor::new());
        let camera = opened(&cell);
        let formats = camera.formats();
        let first = start(&cell, &*camera, &formats[0], CameraOutputs::new()).unwrap();
        let joined = start(&cell, &*camera, &formats[1], CameraOutputs::new()).unwrap();
        assert_eq!(cameras.sessions()[1].picked(), format(640.0, 480.0));
        assert_eq!(*joined.format(&cell.borrow()), format(1920.0, 1080.0));

        first.dispose(&mut cell.borrow_mut());
        joined.dispose(&mut cell.borrow_mut());
        let alone = start(&cell, &*camera, &formats[1], CameraOutputs::new()).unwrap();
        assert_eq!(
            *alone.format(&cell.borrow()),
            format(640.0, 480.0),
            "once no session runs the camera, it runs in the format picked"
        );
    }

    #[test]
    fn a_sessions_listeners_hear_it_interrupted_resume_and_end() {
        let cameras = cameras();
        let cell = app_with(&cameras, &MockCompositor::new());
        let camera = opened(&cell);
        let outputs = CameraOutputs::new().photos(Size::new(1920.0, 1080.0));
        let session = start(&cell, &*camera, &camera.formats()[0], outputs).unwrap();
        let heard = Rc::new(std::cell::Cell::new(0));
        let hearing = Rc::clone(&heard);
        session.add_listener(
            &mut cell.borrow_mut(),
            Listener::new(move |_| hearing.set(hearing.get() + 1)),
        );
        let host = &cameras.sessions()[0];
        let photo = Photo {
            bytes: vec![0xff, 0xd8],
            mime_type: "image/jpeg".to_owned(),
        };
        host.answering_photo(photo.clone());
        assert_eq!(now(session.take_photo(&cell.borrow())), Ok(photo));
        assert!(
            matches!(
                now(session.start_recording(&cell.borrow(), PathBuf::from("/tmp/clip.mov"))),
                Err(MediaError::Failed(_))
            ),
            "movies were not among its outputs"
        );

        let interrupted = CaptureState::Interrupted(Some(CameraInterruption::InUseByAnotherApp));
        host.set_state(interrupted.clone());
        cell.checkpoint();
        assert_eq!(*session.state(&cell.borrow()), interrupted);
        assert_eq!(
            now(session.take_photo(&cell.borrow())),
            Err(MediaError::NotRunning)
        );

        host.set_state(CaptureState::Running);
        cell.checkpoint();
        host.set_state(CaptureState::Ended(CameraError::Unplugged));
        cell.checkpoint();
        assert_eq!(
            *session.state(&cell.borrow()),
            CaptureState::Ended(CameraError::Unplugged)
        );
        assert_eq!(heard.get(), 3);
    }

    #[test]
    fn a_session_records_while_it_runs_with_movies_among_its_outputs() {
        let cameras = cameras();
        let cell = app_with(&cameras, &MockCompositor::new());
        let camera = opened(&cell);
        let outputs = CameraOutputs::new().movies(MovieOptions::default());
        let session = start(&cell, &*camera, &camera.formats()[0], outputs).unwrap();
        let mut recording = session.start_recording(&cell.borrow(), PathBuf::from("/tmp/clip.mov"));
        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(recording.as_mut().poll(&mut context).is_pending());
        session.stop_recording(&cell.borrow());
        assert_eq!(now(recording), Ok(()));
        assert_eq!(
            cameras.sessions()[0].recordings(),
            vec![PathBuf::from("/tmp/clip.mov")]
        );
    }

    #[test]
    fn a_camera_preview_places_the_sessions_preview_layer_at_its_formats_size() {
        let cameras = cameras();
        let compositor = MockCompositor::new();
        let tester = &mut WidgetTester::with_platform(platform_with(&cameras, &compositor));
        tester.view().set_physical_size(Size::new(1200.0, 2400.0));
        let camera = opened(&tester.cell);
        let layer = tester.update(|app| {
            app.platform()
                .compositor()
                .expect("a platform with a compositor")
                .make_layer(false)
        });
        let outputs = CameraOutputs::new().preview(Arc::clone(&layer));
        let session = start(&tester.cell, &*camera, &camera.formats()[0], outputs).unwrap();
        assert!(Arc::ptr_eq(
            &cameras.sessions()[0].preview_layer().unwrap(),
            &layer
        ));
        tester.pump_widget(crate::Center::new().child(CameraPreview::new(session.clone())));
        let scene = tester.view().last_scene().unwrap();
        let slices = waft_embedder::slices(&scene, |_| None);
        let (placed, placement) = slices.composition_layers().next().unwrap();
        assert!(Arc::ptr_eq(placed, &layer));
        assert_eq!(
            placement.bounds().size(),
            Size::new(1200.0, 675.0),
            "as wide as the view lets it be, at the format's aspect, in physical pixels"
        );

        cameras.sessions()[0].set_rotation_angles(90, 90);
        tester.cell.checkpoint();
        assert_eq!(
            tester.update(|app| session.video_rotation_angle_for_horizon_level_preview(app)),
            90
        );
        tester.pump_by(Duration::ZERO);
        let scene = tester.view().last_scene().unwrap();
        let slices = waft_embedder::slices(&scene, |_| None);
        let (_, placement) = slices.composition_layers().next().unwrap();
        let size = placement.bounds().size();
        assert_eq!(
            (size.width(), (size.height() * 10.0).round() / 10.0),
            (1200.0, 2133.3),
            "turned a quarter as the device turns: as wide as the view, at the turned aspect"
        );
    }

    #[test]
    fn a_size_turned_a_quarter_swaps_its_sides() {
        assert_eq!(turned(Size::new(16.0, 9.0), 90), Size::new(9.0, 16.0));
        assert_eq!(turned(Size::new(16.0, 9.0), 270), Size::new(9.0, 16.0));
        assert_eq!(turned(Size::new(16.0, 9.0), 180), Size::new(16.0, 9.0));
    }
}