ferroui-base 0.3.0

The base library of FerroUI: the property system, layout, input, styling, media, text, animation, data binding and the compositor
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::sync::Arc;

use super::OwnedDisposable;
use crate::platform::surfaces::IPlatformRenderSurface;
use crate::platform::{
    IPlatformGraphics, IPlatformGraphicsContext, IPlatformGraphicsReadyStateFeature, IPlatformRenderInterface,
    IPlatformRenderInterfaceContext, IRenderTarget,
};
use crate::reactive::{Disposable, IDisposable};
use crate::utilities::HandlerList;
use crate::{FerroLocator, LocatorExtensions};

/// Owns the backend render context of a renderer and recreates it (together
/// with the graphics context it is bound to) when it is lost.
///
/// Like the platform contracts it manages, it is confined to the thread it
/// was created on.
pub struct PlatformRenderInterfaceContextManager {
    weak_self: Weak<PlatformRenderInterfaceContextManager>,
    /// The platform graphics and their ready state feature: shared with the
    /// thread of the platform by their contracts (`Arc`, `Send + Sync`), so
    /// the thread that renders may hold, call and drop these handles. In
    /// cells because [`release_platform_handles`](Self::release_platform_handles)
    /// empties them with the render interface below.
    graphics: RefCell<Option<Arc<dyn IPlatformGraphics>>>,
    backend: RefCell<Option<Rc<dyn IPlatformRenderInterfaceContext>>>,
    gpu_context: RefCell<Option<OwnedDisposable<dyn IPlatformGraphicsContext>>>,
    ready_state_feature: RefCell<Option<Arc<dyn IPlatformGraphicsReadyStateFeature>>>,
    /// The render interface of the platform, looked up where the manager is
    /// created: the service locator belongs to a thread, and the context may
    /// be created by another one (the render thread).
    ///
    /// The one handle the manager shares with its thread whose count is not
    /// atomic. Nothing outside this type reaches the field: the handle is
    /// cloned from the locator by the thread that has the services (`new`,
    /// `capture_platform_render_interface`), lent by reference
    /// (`with_platform_render_interface`, the creation of the backend
    /// context), and dropped by that thread
    /// (`release_platform_handles`, or the release of the server compositor
    /// where its thread renders too).
    render_interface: RefCell<Option<Rc<dyn IPlatformRenderInterface>>>,
    context_disposed: HandlerList<dyn Fn()>,
    context_created: HandlerList<dyn Fn(&Rc<dyn IPlatformRenderInterfaceContext>)>,
}

impl PlatformRenderInterfaceContextManager {
    pub fn new(graphics: Option<Arc<dyn IPlatformGraphics>>) -> Rc<PlatformRenderInterfaceContextManager> {
        let ready_state_feature = graphics
            .as_ref()
            .and_then(|graphics| graphics.as_feature_provider())
            .and_then(|features| features.try_get_shared::<dyn IPlatformGraphicsReadyStateFeature>());

        Rc::new_cyclic(|weak_self| PlatformRenderInterfaceContextManager {
            weak_self: weak_self.clone(),
            graphics: RefCell::new(graphics),
            backend: RefCell::new(None),
            gpu_context: RefCell::new(None),
            ready_state_feature: RefCell::new(ready_state_feature),
            render_interface: RefCell::new(FerroLocator::current().get_service::<dyn IPlatformRenderInterface>()),
            context_disposed: HandlerList::new(),
            context_created: HandlerList::new(),
        })
    }

    /// Looks the render interface of the platform up in the service locator
    /// of the calling thread, if it is not known yet. Called on the thread
    /// that has the services (the UI thread), before a frame of another
    /// thread needs the render interface.
    pub fn capture_platform_render_interface(&self) {
        let mut render_interface = self.render_interface.borrow_mut();
        if render_interface.is_none() {
            *render_interface = FerroLocator::current().get_service::<dyn IPlatformRenderInterface>();
        }
    }

    /// Whether the render interface of the platform is known.
    pub fn has_platform_render_interface(&self) -> bool {
        self.render_interface.borrow().is_some()
    }

    /// Runs `f` with the render interface of the platform, if it is known.
    ///
    /// The render interface is lent, not handed out: its handle is shared
    /// with the service locator of the UI thread, whose count is not atomic,
    /// so a frame of the render thread must neither clone nor release it.
    pub fn with_platform_render_interface<R>(&self, f: impl FnOnce(&dyn IPlatformRenderInterface) -> R) -> Option<R> {
        let render_interface = self.render_interface.borrow();
        render_interface.as_deref().map(f)
    }

    /// Lets go of the handles the manager shares with the thread that
    /// created it: the platform graphics, its ready state feature and the
    /// render interface. The count of the render interface is not atomic, so
    /// its handle is dropped here, by that thread, when the rest of the
    /// manager is about to be released by the render thread (a compositor
    /// that is confined to it). The other two may be dropped by any thread
    /// and go with it: the manager creates no backend context afterwards.
    pub fn release_platform_handles(&self) {
        let graphics = self.graphics.borrow_mut().take();
        let ready_state_feature = self.ready_state_feature.borrow_mut().take();
        let render_interface = self.render_interface.borrow_mut().take();
        drop((graphics, ready_state_feature, render_interface));
    }

    /// Raised after a lost graphics context has been released.
    pub fn context_disposed(&self, handler: impl Fn() + 'static) -> Rc<dyn IDisposable> {
        let token = self.context_disposed.add(Rc::new(handler));
        let this = self.weak_self.clone();
        Disposable::create(move || {
            if let Some(this) = this.upgrade() {
                this.context_disposed.remove(token);
            }
        })
    }

    /// Raised after a backend context has been created.
    pub fn context_created(
        &self,
        handler: impl Fn(&Rc<dyn IPlatformRenderInterfaceContext>) + 'static,
    ) -> Rc<dyn IDisposable> {
        let token = self.context_created.add(Rc::new(handler));
        let this = self.weak_self.clone();
        Disposable::create(move || {
            if let Some(this) = this.upgrade() {
                this.context_created.remove(token);
            }
        })
    }

    pub fn is_ready(&self) -> bool {
        // A backend context that exists does not need the render interface
        // again. Without one, a thread that cannot find the render interface
        // (the render thread, before the UI thread has looked it up) waits.
        if self.backend.borrow().is_none() && !self.has_platform_render_interface() {
            return false;
        }
        self.ready_state_feature.borrow().as_ref().is_none_or(|feature| feature.is_ready())
    }

    /// Makes sure there is a backend context that is not lost.
    ///
    /// # Panics
    /// Panics when the platform graphics are not ready yet.
    pub fn ensure_valid_backend_context(&self) {
        if !self.is_ready() {
            panic!("Platform graphics isn't ready yet");
        }

        let gpu_context_is_lost = self.gpu_context().is_some_and(|context| context.is_lost());
        if self.backend.borrow().is_none() || gpu_context_is_lost {
            let backend = self.backend.borrow_mut().take();
            if let Some(backend) = backend {
                backend.dispose();
            }

            let gpu_context = self.gpu_context.borrow_mut().take();
            if let Some(mut gpu_context) = gpu_context {
                gpu_context.dispose();
                for (_, handler) in self.context_disposed.snapshot().iter() {
                    handler();
                }
            }

            if let Some(graphics) = &*self.graphics.borrow() {
                if self.ready_state_feature.borrow().as_ref().is_none_or(|feature| feature.uses_contexts()) {
                    let gpu_context = if graphics.uses_shared_context() {
                        OwnedDisposable::new(graphics.get_shared_context(), false)
                    } else {
                        OwnedDisposable::new(graphics.create_context(), true)
                    };
                    *self.gpu_context.borrow_mut() = Some(gpu_context);
                }
            }

            // Lent from the cell: see `with_platform_render_interface`.
            let backend = {
                let render_interface = self.render_interface.borrow();
                match render_interface.as_deref() {
                    Some(render_interface) => render_interface.create_backend_context(self.gpu_context()),
                    None => panic!("Unable to locate the platform render interface."),
                }
            };
            *self.backend.borrow_mut() = Some(backend.clone());
            for (_, handler) in self.context_created.snapshot().iter() {
                handler(&backend);
            }
        }
    }

    /// The backend context; created (or recreated) when needed.
    pub fn value(&self) -> Rc<dyn IPlatformRenderInterfaceContext> {
        self.ensure_valid_backend_context();
        self.backend.borrow().clone().expect("the backend context was just ensured")
    }

    /// The backend context if there is one, as it is: nothing is created,
    /// and a lost context is not replaced. For a thread that may look at the
    /// context but must not create one (the thread of a compositor that is
    /// confined to its render thread).
    pub fn existing_backend_context(&self) -> Option<Rc<dyn IPlatformRenderInterfaceContext>> {
        self.backend.borrow().clone()
    }

    /// The graphics context the backend context is bound to, if any.
    pub fn gpu_context(&self) -> Option<Rc<dyn IPlatformGraphicsContext>> {
        self.gpu_context.borrow().as_ref().map(|context| context.value())
    }

    /// Makes the graphics context current. Disposing the result restores the
    /// previously current context.
    pub fn ensure_current(&self) -> Rc<dyn IDisposable> {
        self.ensure_valid_backend_context();
        match self.gpu_context() {
            Some(gpu_context) => gpu_context.ensure_current(),
            None => Disposable::empty(),
        }
    }

    pub fn create_render_target(&self, surfaces: &[std::sync::Arc<dyn IPlatformRenderSurface>]) -> Rc<dyn IRenderTarget> {
        self.value().create_render_target(surfaces)
    }

    pub fn is_ready_to_create_render_target(&self, surfaces: &[std::sync::Arc<dyn IPlatformRenderSurface>]) -> bool {
        let backend = self.backend.borrow().clone();
        match backend {
            None => self.is_ready(),
            Some(backend) => backend.is_ready_to_create_render_target(surfaces),
        }
    }

    /// Releases the backend context; the next use creates a new one.
    pub fn reset(&self) {
        let backend = self.backend.borrow_mut().take();
        if let Some(backend) = backend {
            backend.dispose();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utilities::ThreadBound;
    use std::sync::atomic::{AtomicBool, Ordering};
    use crate::media::imaging::BitmapInterpolationMode;
    use crate::media::{FillRule, GeometryCombineMode};
    use crate::platform::{
        AlphaFormat, IBitmapImpl, IDrawingContextLayerImpl, IGeometryImpl, IOptionalFeatureProvider,
        IPlatformRenderInterfaceRegion, IRenderTargetBitmapImpl, IStreamGeometryBuilder, IWriteableBitmapImpl,
        PixelFormat,
    };
    use crate::{PixelSize, Point, Rect, Vector};
    use std::any::{Any, TypeId};
    use std::cell::Cell;
    use std::io::Read;

    type Log = Rc<RefCell<Vec<String>>>;

    fn record(log: &Log, entry: impl Into<String>) {
        log.borrow_mut().push(entry.into());
    }

    fn take(log: &Log) -> Vec<String> {
        std::mem::take(&mut *log.borrow_mut())
    }

    struct GraphicsContext {
        id: i32,
        log: Log,
        is_lost: Cell<bool>,
    }

    impl IOptionalFeatureProvider for GraphicsContext {
        fn try_get_feature(&self, _feature_type: TypeId) -> Option<Rc<dyn Any>> {
            None
        }
    }

    impl IPlatformGraphicsContext for GraphicsContext {
        fn is_lost(&self) -> bool {
            self.is_lost.get()
        }

        fn ensure_current(&self) -> Rc<dyn IDisposable> {
            record(&self.log, format!("gpu{}.ensure_current", self.id));
            let log = self.log.clone();
            let id = self.id;
            Disposable::create(move || record(&log, format!("gpu{id}.restore")))
        }

        fn dispose(&self) {
            record(&self.log, format!("gpu{}.dispose", self.id));
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    struct ReadyState {
        is_ready: AtomicBool,
        uses_contexts: AtomicBool,
    }

    impl IPlatformGraphicsReadyStateFeature for ReadyState {
        fn is_ready(&self) -> bool {
            self.is_ready.load(Ordering::SeqCst)
        }

        fn uses_contexts(&self) -> bool {
            self.uses_contexts.load(Ordering::SeqCst)
        }
    }

    /// The platform graphics of these tests: the log and the contexts it
    /// hands out are objects of the test thread, so they are bound to it,
    /// as the display of an implementation that belongs to one thread is.
    struct Graphics {
        state: ThreadBound<GraphicsState>,
        ready_state: Option<Arc<ReadyState>>,
    }

    struct GraphicsState {
        log: Log,
        uses_shared_context: bool,
        shared: Rc<GraphicsContext>,
        created: RefCell<Vec<Rc<GraphicsContext>>>,
    }

    impl std::ops::Deref for Graphics {
        type Target = GraphicsState;

        fn deref(&self) -> &GraphicsState {
            self.state.get()
        }
    }

    impl Graphics {
        fn new(log: &Log, uses_shared_context: bool, ready_state: Option<Arc<ReadyState>>) -> Arc<Graphics> {
            Arc::new(Graphics {
                state: ThreadBound::new(GraphicsState {
                    log: log.clone(),
                    uses_shared_context,
                    shared: Rc::new(GraphicsContext { id: 0, log: log.clone(), is_lost: Cell::new(false) }),
                    created: RefCell::new(Vec::new()),
                }),
                ready_state,
            })
        }
    }

    impl IOptionalFeatureProvider for Graphics {
        fn try_get_feature(&self, feature_type: TypeId) -> Option<Rc<dyn Any>> {
            if feature_type == TypeId::of::<dyn IPlatformGraphicsReadyStateFeature>() {
                let feature: Arc<dyn IPlatformGraphicsReadyStateFeature> = self.ready_state.clone()?;
                return Some(Rc::new(feature));
            }
            None
        }
    }

    impl IPlatformGraphics for Graphics {
        fn uses_shared_context(&self) -> bool {
            self.state.get().uses_shared_context
        }

        fn create_context(&self) -> Rc<dyn IPlatformGraphicsContext> {
            let context = Rc::new(GraphicsContext {
                id: self.created.borrow().len() as i32 + 1,
                log: self.log.clone(),
                is_lost: Cell::new(false),
            });
            record(&self.log, format!("graphics.create_context -> gpu{}", context.id));
            self.created.borrow_mut().push(context.clone());
            context
        }

        fn get_shared_context(&self) -> Rc<dyn IPlatformGraphicsContext> {
            record(&self.log, "graphics.get_shared_context");
            self.shared.clone()
        }

        fn as_feature_provider(&self) -> Option<&dyn IOptionalFeatureProvider> {
            Some(self)
        }
    }

    struct RenderTarget;

    impl IRenderTarget for RenderTarget {
        fn properties(&self) -> crate::platform::RenderTargetProperties {
            Default::default()
        }

        fn create_drawing_context(
            &self,
            _scene_info: &crate::platform::RenderTargetSceneInfo,
        ) -> (Box<dyn crate::platform::IDrawingContextImpl>, crate::platform::RenderTargetDrawingContextProperties)
        {
            unimplemented!()
        }

        fn dispose(&self) {}
    }

    struct BackendContext {
        id: i32,
        log: Log,
        ready_to_create_render_target: Cell<bool>,
    }

    impl IOptionalFeatureProvider for BackendContext {
        fn try_get_feature(&self, _feature_type: TypeId) -> Option<Rc<dyn Any>> {
            None
        }
    }

    impl IPlatformRenderInterfaceContext for BackendContext {
        fn create_render_target(&self, surfaces: &[std::sync::Arc<dyn IPlatformRenderSurface>]) -> Rc<dyn IRenderTarget> {
            record(&self.log, format!("backend{}.create_render_target({})", self.id, surfaces.len()));
            Rc::new(RenderTarget)
        }

        fn create_offscreen_render_target(
            &self,
            _pixel_size: PixelSize,
            _scaling: Vector,
            _enable_text_antialiasing: bool,
        ) -> Rc<dyn IDrawingContextLayerImpl> {
            unimplemented!()
        }

        fn is_lost(&self) -> bool {
            false
        }

        fn max_offscreen_render_target_pixel_size(&self) -> Option<PixelSize> {
            None
        }

        fn is_ready_to_create_render_target(&self, _surfaces: &[std::sync::Arc<dyn IPlatformRenderSurface>]) -> bool {
            self.ready_to_create_render_target.get()
        }

        fn dispose(&self) {
            record(&self.log, format!("backend{}.dispose", self.id));
        }
    }

    struct RenderInterface {
        log: Log,
        backends: RefCell<Vec<Rc<BackendContext>>>,
    }

    impl IPlatformRenderInterface for RenderInterface {
        fn create_backend_context(
            &self,
            graphics_api_context: Option<Rc<dyn IPlatformGraphicsContext>>,
        ) -> Rc<dyn IPlatformRenderInterfaceContext> {
            let backend = Rc::new(BackendContext {
                id: self.backends.borrow().len() as i32 + 1,
                log: self.log.clone(),
                ready_to_create_render_target: Cell::new(true),
            });
            let gpu = match &graphics_api_context {
                Some(context) => {
                    format!("gpu{}", context.as_any().downcast_ref::<GraphicsContext>().unwrap().id)
                }
                None => "software".to_string(),
            };
            record(&self.log, format!("create_backend_context({gpu}) -> backend{}", backend.id));
            self.backends.borrow_mut().push(backend.clone());
            backend
        }

        fn build_glyph_run_geometry(&self, _glyph_run: &crate::media::GlyphRun) -> Arc<dyn IGeometryImpl> {
            unimplemented!()
        }

        fn create_glyph_run(
            &self,
            _glyph_typeface: &Rc<crate::media::GlyphTypeface>,
            _font_rendering_em_size: f64,
            _glyph_infos: &[crate::media::text_formatting::GlyphInfo],
            _baseline_origin: Point,
        ) -> std::sync::Arc<dyn crate::platform::IGlyphRunImpl> {
            unimplemented!()
        }

        fn create_ellipse_geometry(&self, _rect: Rect) -> Arc<dyn IGeometryImpl> {
            unimplemented!()
        }

        fn create_line_geometry(&self, _p1: Point, _p2: Point) -> Arc<dyn IGeometryImpl> {
            unimplemented!()
        }

        fn create_rectangle_geometry(&self, _rect: Rect) -> Arc<dyn IGeometryImpl> {
            unimplemented!()
        }

        fn create_stream_geometry_builder(&self, _source: Option<&dyn IGeometryImpl>) -> Box<dyn IStreamGeometryBuilder> {
            unimplemented!()
        }

        fn create_geometry_group(
            &self,
            _fill_rule: FillRule,
            _children: &[Arc<dyn IGeometryImpl>],
        ) -> Arc<dyn IGeometryImpl> {
            unimplemented!()
        }

        fn create_combined_geometry(
            &self,
            _combine_mode: GeometryCombineMode,
            _g1: Arc<dyn IGeometryImpl>,
            _g2: Arc<dyn IGeometryImpl>,
        ) -> Arc<dyn IGeometryImpl> {
            unimplemented!()
        }

        fn create_render_target_bitmap(&self, _size: PixelSize, _dpi: Vector) -> std::sync::Arc<dyn IRenderTargetBitmapImpl> {
            unimplemented!()
        }

        fn create_writeable_bitmap(
            &self,
            _size: PixelSize,
            _dpi: Vector,
            _format: PixelFormat,
            _alpha_format: AlphaFormat,
        ) -> std::sync::Arc<dyn IWriteableBitmapImpl> {
            unimplemented!()
        }

        fn load_bitmap_from_file(&self, _file_name: &str) -> std::io::Result<std::sync::Arc<crate::platform::SharedBitmapImpl>> {
            unimplemented!()
        }

        fn load_bitmap(&self, _stream: &mut dyn Read) -> std::io::Result<std::sync::Arc<crate::platform::SharedBitmapImpl>> {
            unimplemented!()
        }

        fn load_writeable_bitmap_to_width(
            &self,
            _stream: &mut dyn Read,
            _width: i32,
            _interpolation_mode: BitmapInterpolationMode,
        ) -> std::io::Result<std::sync::Arc<dyn IWriteableBitmapImpl>> {
            unimplemented!()
        }

        fn load_writeable_bitmap_to_height(
            &self,
            _stream: &mut dyn Read,
            _height: i32,
            _interpolation_mode: BitmapInterpolationMode,
        ) -> std::io::Result<std::sync::Arc<dyn IWriteableBitmapImpl>> {
            unimplemented!()
        }

        fn load_writeable_bitmap_from_file(&self, _file_name: &str) -> std::io::Result<std::sync::Arc<dyn IWriteableBitmapImpl>> {
            unimplemented!()
        }

        fn load_writeable_bitmap(&self, _stream: &mut dyn Read) -> std::io::Result<std::sync::Arc<dyn IWriteableBitmapImpl>> {
            unimplemented!()
        }

        fn load_bitmap_to_width(
            &self,
            _stream: &mut dyn Read,
            _width: i32,
            _interpolation_mode: BitmapInterpolationMode,
        ) -> std::io::Result<std::sync::Arc<crate::platform::SharedBitmapImpl>> {
            unimplemented!()
        }

        fn load_bitmap_to_height(
            &self,
            _stream: &mut dyn Read,
            _height: i32,
            _interpolation_mode: BitmapInterpolationMode,
        ) -> std::io::Result<std::sync::Arc<crate::platform::SharedBitmapImpl>> {
            unimplemented!()
        }

        fn resize_bitmap(
            &self,
            _bitmap_impl: &dyn IBitmapImpl,
            _destination_size: PixelSize,
            _interpolation_mode: BitmapInterpolationMode,
        ) -> std::sync::Arc<crate::platform::SharedBitmapImpl> {
            unimplemented!()
        }

        fn load_bitmap_from_pixels(
            &self,
            _format: PixelFormat,
            _alpha_format: AlphaFormat,
            _data: &[u8],
            _size: PixelSize,
            _dpi: Vector,
            _stride: i32,
        ) -> std::sync::Arc<crate::platform::SharedBitmapImpl> {
            unimplemented!()
        }

        fn supports_individual_round_rects(&self) -> bool {
            false
        }

        fn default_alpha_format(&self) -> AlphaFormat {
            unimplemented!()
        }

        fn default_pixel_format(&self) -> PixelFormat {
            unimplemented!()
        }

        fn is_supported_bitmap_pixel_format(&self, _format: PixelFormat) -> bool {
            false
        }

        fn supports_regions(&self) -> bool {
            false
        }

        fn create_region(&self) -> Rc<dyn IPlatformRenderInterfaceRegion> {
            unimplemented!()
        }
    }

    /// Registers a render interface for the test and restores the locator
    /// afterwards.
    struct Fixture {
        log: Log,
        render_interface: Rc<RenderInterface>,
        scope: Rc<dyn IDisposable>,
    }

    impl Fixture {
        fn new() -> Fixture {
            let log: Log = Rc::new(RefCell::new(Vec::new()));
            let scope = FerroLocator::enter_scope();
            let render_interface = Rc::new(RenderInterface { log: log.clone(), backends: RefCell::new(Vec::new()) });
            FerroLocator::current_mutable().bind::<dyn IPlatformRenderInterface>().to_constant(render_interface.clone());
            Fixture { log, render_interface, scope }
        }

        fn manager(&self, graphics: Option<Arc<Graphics>>) -> Rc<PlatformRenderInterfaceContextManager> {
            let manager =
                PlatformRenderInterfaceContextManager::new(graphics.map(|graphics| graphics as Arc<dyn IPlatformGraphics>));
            let log = self.log.clone();
            manager.context_disposed(move || record(&log, "ContextDisposed"));
            let log = self.log.clone();
            let render_interface = Rc::downgrade(&self.render_interface);
            manager.context_created(move |context| {
                let render_interface = render_interface.upgrade().unwrap();
                let backends = render_interface.backends.borrow();
                let created = backends.last().unwrap();
                assert!(std::ptr::eq(Rc::as_ptr(context) as *const (), Rc::as_ptr(created) as *const ()));
                record(&log, format!("ContextCreated(backend{})", created.id));
            });
            manager
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            self.scope.dispose();
        }
    }

    #[test]
    fn software_backend_is_created_once_without_a_graphics_context() {
        let fixture = Fixture::new();
        let manager = fixture.manager(None);
        assert!(manager.is_ready());
        assert!(manager.gpu_context().is_none());
        assert!(take(&fixture.log).is_empty());

        let value = manager.value();
        assert_eq!(take(&fixture.log), ["create_backend_context(software) -> backend1", "ContextCreated(backend1)"]);
        assert!(manager.gpu_context().is_none());

        assert!(Rc::ptr_eq(&value, &manager.value()));
        manager.ensure_valid_backend_context();
        // Without a graphics context there is nothing to make current.
        manager.ensure_current().dispose();
        assert!(take(&fixture.log).is_empty());
    }

    #[test]
    fn owned_graphics_context_is_recreated_when_lost() {
        let fixture = Fixture::new();
        let graphics = Graphics::new(&fixture.log, false, None);
        let manager = fixture.manager(Some(graphics.clone()));

        manager.ensure_valid_backend_context();
        assert_eq!(
            take(&fixture.log),
            [
                "graphics.create_context -> gpu1",
                "create_backend_context(gpu1) -> backend1",
                "ContextCreated(backend1)"
            ]
        );
        let gpu_context = manager.gpu_context().unwrap();
        assert!(std::ptr::eq(
            Rc::as_ptr(&gpu_context) as *const (),
            Rc::as_ptr(&graphics.created.borrow()[0]) as *const ()
        ));

        let current = manager.ensure_current();
        current.dispose();
        assert_eq!(take(&fixture.log), ["gpu1.ensure_current", "gpu1.restore"]);

        graphics.created.borrow()[0].is_lost.set(true);
        let value = manager.value();
        assert_eq!(
            take(&fixture.log),
            [
                "backend1.dispose",
                "gpu1.dispose",
                "ContextDisposed",
                "graphics.create_context -> gpu2",
                "create_backend_context(gpu2) -> backend2",
                "ContextCreated(backend2)"
            ]
        );
        assert!(std::ptr::eq(
            Rc::as_ptr(&value) as *const (),
            Rc::as_ptr(&fixture.render_interface.backends.borrow()[1]) as *const ()
        ));
    }

    #[test]
    fn shared_graphics_context_is_not_disposed() {
        let fixture = Fixture::new();
        let graphics = Graphics::new(&fixture.log, true, None);
        let manager = fixture.manager(Some(graphics.clone()));

        manager.ensure_valid_backend_context();
        assert_eq!(
            take(&fixture.log),
            ["graphics.get_shared_context", "create_backend_context(gpu0) -> backend1", "ContextCreated(backend1)"]
        );

        graphics.shared.is_lost.set(true);
        // The lost shared context is handed out again by the graphics, so
        // the backend is recreated on every use while it stays lost.
        manager.ensure_valid_backend_context();
        assert_eq!(
            take(&fixture.log),
            [
                "backend1.dispose",
                "ContextDisposed",
                "graphics.get_shared_context",
                "create_backend_context(gpu0) -> backend2",
                "ContextCreated(backend2)"
            ]
        );
    }

    #[test]
    fn reset_releases_the_backend_but_keeps_the_graphics_context() {
        let fixture = Fixture::new();
        let graphics = Graphics::new(&fixture.log, false, None);
        let manager = fixture.manager(Some(graphics));
        manager.ensure_valid_backend_context();
        take(&fixture.log);

        manager.reset();
        manager.reset();
        assert_eq!(take(&fixture.log), ["backend1.dispose"]);
        assert!(manager.gpu_context().is_some());

        // The graphics context is released and recreated with the backend.
        manager.ensure_valid_backend_context();
        assert_eq!(
            take(&fixture.log),
            [
                "gpu1.dispose",
                "ContextDisposed",
                "graphics.create_context -> gpu2",
                "create_backend_context(gpu2) -> backend2",
                "ContextCreated(backend2)"
            ]
        );
    }

    #[test]
    fn create_render_target_uses_the_backend() {
        let fixture = Fixture::new();
        let manager = fixture.manager(None);
        // Before a backend exists, readiness is the readiness of the graphics.
        assert!(manager.is_ready_to_create_render_target(&[]));
        assert!(take(&fixture.log).is_empty());

        manager.create_render_target(&[]);
        assert_eq!(
            take(&fixture.log),
            [
                "create_backend_context(software) -> backend1",
                "ContextCreated(backend1)",
                "backend1.create_render_target(0)"
            ]
        );

        fixture.render_interface.backends.borrow()[0].ready_to_create_render_target.set(false);
        assert!(!manager.is_ready_to_create_render_target(&[]));
    }

    #[test]
    fn ready_state_feature_controls_readiness_and_context_use() {
        let fixture = Fixture::new();
        let ready_state =
            Arc::new(ReadyState { is_ready: AtomicBool::new(false), uses_contexts: AtomicBool::new(false) });
        let graphics = Graphics::new(&fixture.log, false, Some(ready_state.clone()));
        let manager = fixture.manager(Some(graphics));

        assert!(!manager.is_ready());
        assert!(!manager.is_ready_to_create_render_target(&[]));
        let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| manager.ensure_valid_backend_context()));
        assert!(failed.is_err());
        assert!(take(&fixture.log).is_empty());

        ready_state.is_ready.store(true, Ordering::SeqCst);
        assert!(manager.is_ready());
        manager.ensure_valid_backend_context();
        // The graphics do not use contexts: the backend is created without one.
        assert_eq!(take(&fixture.log), ["create_backend_context(software) -> backend1", "ContextCreated(backend1)"]);
        assert!(manager.gpu_context().is_none());

        manager.reset();
        ready_state.uses_contexts.store(true, Ordering::SeqCst);
        manager.ensure_valid_backend_context();
        assert_eq!(
            take(&fixture.log),
            [
                "backend1.dispose",
                "graphics.create_context -> gpu1",
                "create_backend_context(gpu1) -> backend2",
                "ContextCreated(backend2)"
            ]
        );
    }

    #[test]
    fn event_subscriptions_can_be_disposed() {
        let fixture = Fixture::new();
        let manager = PlatformRenderInterfaceContextManager::new(None);
        let created = Rc::new(Cell::new(0));
        let c = created.clone();
        let subscription = manager.context_created(move |_| c.set(c.get() + 1));
        manager.ensure_valid_backend_context();
        assert_eq!(created.get(), 1);

        subscription.dispose();
        manager.reset();
        manager.ensure_valid_backend_context();
        assert_eq!(created.get(), 1);
        drop(fixture);
    }
}