-
Notifications
You must be signed in to change notification settings - Fork 543
/
software_renderer.rs
2652 lines (2416 loc) · 106 KB
/
software_renderer.rs
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-1.2 OR LicenseRef-Slint-commercial
//! This module contains the [`SoftwareRenderer`] and related types.
//!
//! It is only enabled when the `renderer-software` Slint feature is enabled.
#![warn(missing_docs)]
mod draw_functions;
mod fixed;
mod fonts;
use self::fonts::GlyphRenderer;
use crate::api::Window;
use crate::graphics::rendering_metrics_collector::{RefreshMode, RenderingMetricsCollector};
use crate::graphics::{BorderRadius, PixelFormat, SharedImageBuffer, SharedPixelBuffer};
use crate::item_rendering::{CachedRenderingData, DirtyRegion, RenderBorderRectangle, RenderImage};
use crate::items::{ItemRc, TextOverflow};
use crate::lengths::{
LogicalBorderRadius, LogicalLength, LogicalPoint, LogicalRect, LogicalSize, LogicalVector,
PhysicalPx, PointLengths, RectLengths, ScaleFactor, SizeLengths,
};
use crate::renderer::{Renderer, RendererSealed};
use crate::textlayout::{AbstractFont, FontMetrics, TextParagraphLayout};
use crate::window::{WindowAdapter, WindowInner};
use crate::{Brush, Color, Coord, ImageInner, StaticTextures};
use alloc::rc::{Rc, Weak};
#[cfg(not(feature = "std"))]
use alloc::{vec, vec::Vec};
use core::cell::{Cell, RefCell};
use core::pin::Pin;
use euclid::Length;
use fixed::Fixed;
#[allow(unused)]
use num_traits::Float;
use num_traits::NumCast;
pub use draw_functions::{PremultipliedRgbaColor, Rgb565Pixel, TargetPixel};
type PhysicalLength = euclid::Length<i16, PhysicalPx>;
type PhysicalRect = euclid::Rect<i16, PhysicalPx>;
type PhysicalSize = euclid::Size2D<i16, PhysicalPx>;
type PhysicalPoint = euclid::Point2D<i16, PhysicalPx>;
type PhysicalBorderRadius = BorderRadius<i16, PhysicalPx>;
/// This enum describes which parts of the buffer passed to the [`SoftwareRenderer`] may be re-used to speed up painting.
// FIXME: #[non_exhaustive] #3023
#[derive(PartialEq, Eq, Debug, Clone, Default, Copy)]
pub enum RepaintBufferType {
#[default]
/// The full window is always redrawn. No attempt at partial rendering will be made.
NewBuffer,
/// Only redraw the parts that have changed since the previous call to render().
///
/// This variant assumes that the same buffer is passed on every call to render() and
/// that it still contains the previously rendered frame.
ReusedBuffer,
/// Redraw the part that have changed since the last two frames were drawn.
///
/// This is used when using double buffering and swapping of the buffers.
SwappedBuffers,
}
/// This module is just a trick to make the Window public only when `feature = "software-renderer-rotation"`
#[allow(unused)]
mod internal {
use super::*;
/// This enum describes the rotation that should be applied to the contents rendered by the software renderer.
///
/// Argument to be passed in [`SoftwareRenderer::set_rendering_rotation`].
#[non_exhaustive]
#[derive(Default, Copy, Clone, Eq, PartialEq, Debug)]
pub enum RenderingRotation {
/// No rotation
#[default]
NoRotation,
/// Rotate 90° to the right
Rotate90,
/// 180° rotation (upside-down)
Rotate180,
/// Rotate 90° to the left
Rotate270,
}
}
#[cfg(feature = "software-renderer-rotation")]
pub use internal::RenderingRotation;
#[cfg(not(feature = "software-renderer-rotation"))]
use internal::RenderingRotation;
impl RenderingRotation {
fn is_transpose(self) -> bool {
matches!(self, Self::Rotate90 | Self::Rotate270)
}
fn mirror_width(self) -> bool {
matches!(self, Self::Rotate270 | Self::Rotate180)
}
fn mirror_height(self) -> bool {
matches!(self, Self::Rotate90 | Self::Rotate180)
}
/// Angle of the rotation in degrees
fn angle(self) -> f32 {
match self {
RenderingRotation::NoRotation => 0.,
RenderingRotation::Rotate90 => 90.,
RenderingRotation::Rotate180 => 180.,
RenderingRotation::Rotate270 => 270.,
}
}
}
#[derive(Copy, Clone)]
struct RotationInfo {
orientation: RenderingRotation,
screen_size: PhysicalSize,
}
/// Extension trait for euclid type to transpose coordinates (swap x and y, as well as width and height)
trait Transform {
/// Return a copy of Self whose coordinate are swapped (x swapped with y)
#[must_use]
fn transformed(self, info: RotationInfo) -> Self;
}
impl<T: Copy + NumCast + core::ops::Sub<Output = T>> Transform for euclid::Point2D<T, PhysicalPx> {
fn transformed(mut self, info: RotationInfo) -> Self {
if info.orientation.mirror_width() {
self.x = T::from(info.screen_size.width).unwrap() - self.x - T::from(1).unwrap()
}
if info.orientation.mirror_height() {
self.y = T::from(info.screen_size.height).unwrap() - self.y - T::from(1).unwrap()
}
if info.orientation.is_transpose() {
core::mem::swap(&mut self.x, &mut self.y);
}
self
}
}
impl<T: Copy> Transform for euclid::Size2D<T, PhysicalPx> {
fn transformed(mut self, info: RotationInfo) -> Self {
if info.orientation.is_transpose() {
core::mem::swap(&mut self.width, &mut self.height);
}
self
}
}
impl<T: Copy + NumCast + core::ops::Sub<Output = T>> Transform for euclid::Rect<T, PhysicalPx> {
fn transformed(self, info: RotationInfo) -> Self {
let one = T::from(1).unwrap();
let mut origin = self.origin.transformed(info);
let size = self.size.transformed(info);
if info.orientation.mirror_width() {
origin.y = origin.y - (size.height - one);
}
if info.orientation.mirror_height() {
origin.x = origin.x - (size.width - one);
}
Self::new(origin, size)
}
}
impl<T: Copy> Transform for BorderRadius<T, PhysicalPx> {
fn transformed(self, info: RotationInfo) -> Self {
match info.orientation {
RenderingRotation::NoRotation => self,
RenderingRotation::Rotate90 => {
Self::new(self.bottom_left, self.top_left, self.top_right, self.bottom_right)
}
RenderingRotation::Rotate180 => {
Self::new(self.bottom_right, self.bottom_left, self.top_left, self.top_right)
}
RenderingRotation::Rotate270 => {
Self::new(self.top_right, self.bottom_right, self.bottom_left, self.top_left)
}
}
}
}
/// This trait defines a bi-directional interface between Slint and your code to send lines to your screen, when using
/// the [`SoftwareRenderer::render_by_line`] function.
///
/// * Through the associated `TargetPixel` type Slint knows how to create and manipulate pixels without having to know
/// the exact device-specific binary representation and operations for blending.
/// * Through the `process_line` function Slint notifies you when a line can be rendered and provides a callback that
/// you can invoke to fill a slice of pixels for the given line.
///
/// See the [`render_by_line`](SoftwareRenderer::render_by_line) documentation for an example.
pub trait LineBufferProvider {
/// The pixel type of the buffer
type TargetPixel: TargetPixel;
/// Called once per line, you will have to call the render_fn back with the buffer.
///
/// The `line` is the y position of the line to be drawn.
/// The `range` is the range within the line that is going to be rendered (eg, within the dirty region)
/// The `render_fn` function should be called to render the line, passing the buffer
/// corresponding to the specified line and range.
fn process_line(
&mut self,
line: usize,
range: core::ops::Range<usize>,
render_fn: impl FnOnce(&mut [Self::TargetPixel]),
);
}
#[cfg(not(cbindgen))]
const PHYSICAL_REGION_MAX_SIZE: usize = DirtyRegion::MAX_COUNT;
// cbindgen can't understand associated const correctly, so hardcode the value
#[cfg(cbindgen)]
pub const PHYSICAL_REGION_MAX_SIZE: usize = 3;
const _: () = {
assert!(PHYSICAL_REGION_MAX_SIZE == 3);
assert!(DirtyRegion::MAX_COUNT == 3);
};
/// Represents a rectangular region on the screen, used for partial rendering.
///
/// The region may be composed of multiple sub-regions.
#[derive(Clone, Debug, Default)]
#[repr(C)]
pub struct PhysicalRegion {
rectangles: [euclid::Box2D<i16, PhysicalPx>; PHYSICAL_REGION_MAX_SIZE],
count: usize,
}
impl PhysicalRegion {
fn iter_box(&self) -> impl Iterator<Item = euclid::Box2D<i16, PhysicalPx>> + '_ {
(0..self.count).map(|x| self.rectangles[x])
}
fn bounding_rect(&self) -> PhysicalRect {
if self.count == 0 {
return Default::default();
}
let mut r = self.rectangles[0];
for i in 1..self.count {
r = r.union(&self.rectangles[i]);
}
r.to_rect()
}
/// Returns the size of the bounding box of this region.
pub fn bounding_box_size(&self) -> crate::api::PhysicalSize {
let bb = self.bounding_rect();
crate::api::PhysicalSize { width: bb.width() as _, height: bb.height() as _ }
}
/// Returns the origin of the bounding box of this region.
pub fn bounding_box_origin(&self) -> crate::api::PhysicalPosition {
let bb = self.bounding_rect();
crate::api::PhysicalPosition { x: bb.origin.x as _, y: bb.origin.y as _ }
}
/// Returns an iterator over the rectangles in this region.
/// Each rectangle is represented by its position and its size.
pub fn iter(
&self,
) -> impl Iterator<Item = (crate::api::PhysicalPosition, crate::api::PhysicalSize)> + '_ {
self.iter_box().map(|r| {
let r = r.to_rect();
(
crate::api::PhysicalPosition { x: r.origin.x as _, y: r.origin.y as _ },
crate::api::PhysicalSize { width: r.width() as _, height: r.height() as _ },
)
})
}
}
/// Computes what are the x ranges that intersects the region for specified y line.
///
/// This uses a mutable reference to a Vec so that the memory is re-used between calls.
///
/// Returns the y position until which this range is valid
fn region_line_ranges(
region: &PhysicalRegion,
line: i16,
line_ranges: &mut Vec<core::ops::Range<i16>>,
) -> Option<i16> {
line_ranges.clear();
let mut next_validity = None::<i16>;
for geom in region.iter_box() {
if geom.is_empty() {
continue;
}
if geom.y_range().contains(&line) {
match &mut next_validity {
Some(val) => *val = geom.max.y.min(*val),
None => next_validity = Some(geom.max.y),
}
let mut tmp = Some(geom.x_range());
line_ranges.retain_mut(|it| {
if let Some(r) = &mut tmp {
if it.end < r.start {
return true;
} else if it.start <= r.start {
if it.end >= r.end {
tmp = None;
return true;
}
r.start = it.start;
return false;
} else if it.start <= r.end {
if it.end <= r.end {
return false;
} else {
it.start = r.start;
tmp = None;
return true;
}
} else {
core::mem::swap(it, r);
return true;
}
} else {
return true;
}
});
if let Some(r) = tmp {
line_ranges.push(r);
}
continue;
} else {
if geom.min.y >= line {
match &mut next_validity {
Some(val) => *val = geom.min.y.min(*val),
None => next_validity = Some(geom.min.y),
}
}
}
}
// check that current items are properly sorted
debug_assert!(line_ranges.windows(2).all(|x| x[0].end < x[1].start));
next_validity
}
/// A Renderer that do the rendering in software
///
/// The renderer can remember what items needs to be redrawn from the previous iteration.
///
/// There are two kind of possible rendering
/// 1. Using [`render()`](Self::render()) to render the window in a buffer
/// 2. Using [`render_by_line()`](Self::render()) to render the window line by line. This
/// is only useful if the device does not have enough memory to render the whole window
/// in one single buffer
pub struct SoftwareRenderer {
partial_cache: RefCell<crate::item_rendering::PartialRenderingCache>,
repaint_buffer_type: Cell<RepaintBufferType>,
/// This is the area which we are going to redraw in the next frame, no matter if the items are dirty or not
force_dirty: RefCell<DirtyRegion>,
/// Force a redraw in the next frame, no matter what's dirty. Use only as a last resort.
force_screen_refresh: Cell<bool>,
/// This is the area which was dirty on the previous frame.
/// Only used if repaint_buffer_type == RepaintBufferType::SwappedBuffers
prev_frame_dirty: Cell<DirtyRegion>,
maybe_window_adapter: RefCell<Option<Weak<dyn crate::window::WindowAdapter>>>,
rotation: Cell<RenderingRotation>,
rendering_metrics_collector: Option<Rc<RenderingMetricsCollector>>,
}
impl Default for SoftwareRenderer {
fn default() -> Self {
Self {
partial_cache: Default::default(),
repaint_buffer_type: Default::default(),
force_dirty: Default::default(),
force_screen_refresh: Default::default(),
prev_frame_dirty: Default::default(),
maybe_window_adapter: Default::default(),
rotation: Default::default(),
rendering_metrics_collector: RenderingMetricsCollector::new("software"),
}
}
}
impl SoftwareRenderer {
/// Create a new Renderer
pub fn new() -> Self {
Default::default()
}
/// Create a new SoftwareRenderer.
///
/// The `repaint_buffer_type` parameter specify what kind of buffer are passed to [`Self::render`]
pub fn new_with_repaint_buffer_type(repaint_buffer_type: RepaintBufferType) -> Self {
Self { repaint_buffer_type: repaint_buffer_type.into(), ..Default::default() }
}
/// Change the what kind of buffer is being passed to [`Self::render`]
///
/// This may clear the internal caches
pub fn set_repaint_buffer_type(&self, repaint_buffer_type: RepaintBufferType) {
if self.repaint_buffer_type.replace(repaint_buffer_type) != repaint_buffer_type {
self.partial_cache.borrow_mut().clear();
}
}
/// Returns the kind of buffer that must be passed to [`Self::render`]
pub fn repaint_buffer_type(&self) -> RepaintBufferType {
self.repaint_buffer_type.get()
}
/// Set how the window need to be rotated in the buffer.
///
/// This is typically used to implement screen rotation in software
#[cfg(feature = "software-renderer-rotation")]
// This API is under a feature flag because it is experimental for now.
// It should be a property of the Window instead (set via dispatch_event?)
pub fn set_rendering_rotation(&self, rotation: RenderingRotation) {
self.rotation.set(rotation)
}
/// Return the current rotation. See [`Self::set_rendering_rotation()`]
#[cfg(feature = "software-renderer-rotation")]
pub fn rendering_rotation(&self) -> RenderingRotation {
self.rotation.get()
}
/// Internal function to apply a dirty region depending on the dirty_tracking_policy.
/// Returns the region to actually draw.
fn apply_dirty_region(&self, dirty_region: &mut DirtyRegion, screen_size: LogicalSize) {
let screen_region = LogicalRect::from_size(screen_size);
if self.force_screen_refresh.take() {
*dirty_region = screen_region.into();
}
*dirty_region = match self.repaint_buffer_type() {
RepaintBufferType::NewBuffer => screen_region.into(),
RepaintBufferType::ReusedBuffer => dirty_region.clone(),
RepaintBufferType::SwappedBuffers => {
dirty_region.union(&self.prev_frame_dirty.replace(dirty_region.clone()))
}
}
.intersection(screen_region)
}
/// Render the window to the given frame buffer.
///
/// The renderer uses a cache internally and will only render the part of the window
/// which are dirty. The `extra_draw_region` is an extra region which will also
/// be rendered. (eg: the previous dirty region in case of double buffering)
/// This function returns the region that was rendered.
///
/// The pixel_stride is the size (in pixels) between two lines in the buffer.
/// It is equal `width` if the screen is not rotated, and `height` if the screen is rotated by 90°.
/// The buffer needs to be big enough to contain the window, so its size must be at least
/// `pixel_stride * height`, or `pixel_stride * width` if the screen is rotated by 90°.
///
/// Returns the physical dirty region for this frame, excluding the extra_draw_region,
/// in the window frame of reference. It is affected by the screen rotation.
pub fn render(&self, buffer: &mut [impl TargetPixel], pixel_stride: usize) -> PhysicalRegion {
let Some(window) = self.maybe_window_adapter.borrow().as_ref().and_then(|w| w.upgrade())
else {
return Default::default();
};
let window_inner = WindowInner::from_pub(window.window());
let factor = ScaleFactor::new(window_inner.scale_factor());
let rotation = self.rotation.get();
let (size, background) = if let Some(window_item) =
window_inner.window_item().as_ref().map(|item| item.as_pin_ref())
{
(
(LogicalSize::from_lengths(window_item.width(), window_item.height()).cast()
* factor)
.cast(),
window_item.background(),
)
} else if rotation.is_transpose() {
(euclid::size2((buffer.len() / pixel_stride) as _, pixel_stride as _), Brush::default())
} else {
(euclid::size2(pixel_stride as _, (buffer.len() / pixel_stride) as _), Brush::default())
};
if size.is_empty() {
return Default::default();
}
assert!(
if rotation.is_transpose() {
pixel_stride >= size.height as usize && buffer.len() >= (size.width as usize * pixel_stride + size.height as usize) - pixel_stride
} else {
pixel_stride >= size.width as usize && buffer.len() >= (size.height as usize * pixel_stride + size.width as usize) - pixel_stride
},
"buffer of size {} with stride {pixel_stride} is too small to handle a window of size {size:?}", buffer.len()
);
let buffer_renderer = SceneBuilder::new(
size,
factor,
window_inner,
RenderToBuffer {
buffer,
stride: pixel_stride,
dirty_range_cache: vec![],
dirty_region: Default::default(),
},
rotation,
);
let mut renderer = crate::item_rendering::PartialRenderer::new(
&self.partial_cache,
self.force_dirty.take(),
buffer_renderer,
);
window_inner
.draw_contents(|components| {
let logical_size = (size.cast() / factor).cast();
for (component, origin) in components {
renderer.compute_dirty_regions(component, *origin, logical_size);
}
self.apply_dirty_region(&mut renderer.dirty_region, logical_size);
let rotation = RotationInfo { orientation: rotation, screen_size: size };
let mut i = renderer.dirty_region.iter().map(|r| {
(r.cast() * factor).to_rect().round_out().cast().transformed(rotation)
});
let dirty_region = PhysicalRegion {
rectangles: core::array::from_fn(|_| i.next().unwrap_or_default().to_box2d()),
count: renderer.dirty_region.iter().count(),
};
drop(i);
let mut bg = TargetPixel::background();
// TODO: gradient background
TargetPixel::blend(&mut bg, background.color().into());
let mut line = 0;
while let Some(next) = region_line_ranges(
&dirty_region,
line,
&mut renderer.actual_renderer.processor.dirty_range_cache,
) {
for l in line..next {
for r in &renderer.actual_renderer.processor.dirty_range_cache {
renderer.actual_renderer.processor.buffer[l as usize * pixel_stride..]
[r.start as usize..r.end as usize]
.fill(bg);
}
}
line = next;
}
renderer.actual_renderer.processor.dirty_region = dirty_region.clone();
for (component, origin) in components {
crate::item_rendering::render_component_items(
component,
&mut renderer,
*origin,
);
}
if let Some(metrics) = &self.rendering_metrics_collector {
metrics.measure_frame_rendered(&mut renderer);
if metrics.refresh_mode() == RefreshMode::FullSpeed {
self.force_screen_refresh.set(true);
}
}
dirty_region
})
.unwrap_or_default()
}
/// Render the window, line by line, into the line buffer provided by the [`LineBufferProvider`].
///
/// The renderer uses a cache internally and will only render the part of the window
/// which are dirty, depending on the dirty tracking policy set in [`SoftwareRenderer::new`]
/// This function returns the physical region that was rendered considering the rotation.
///
/// The [`LineBufferProvider::process_line()`] function will be called for each line and should
/// provide a buffer to draw into.
///
/// As an example, let's imagine we want to render into a plain buffer.
/// (You wouldn't normally use `render_by_line` for that because the [`Self::render`] would
/// then be more efficient)
///
/// ```rust
/// # use i_slint_core::software_renderer::{LineBufferProvider, SoftwareRenderer, Rgb565Pixel};
/// # fn xxx<'a>(the_frame_buffer: &'a mut [Rgb565Pixel], display_width: usize, renderer: &SoftwareRenderer) {
/// struct FrameBuffer<'a>{ frame_buffer: &'a mut [Rgb565Pixel], stride: usize }
/// impl<'a> LineBufferProvider for FrameBuffer<'a> {
/// type TargetPixel = Rgb565Pixel;
/// fn process_line(
/// &mut self,
/// line: usize,
/// range: core::ops::Range<usize>,
/// render_fn: impl FnOnce(&mut [Self::TargetPixel]),
/// ) {
/// let line_begin = line * self.stride;
/// render_fn(&mut self.frame_buffer[line_begin..][range]);
/// // The line has been rendered and there could be code here to
/// // send the pixel to the display
/// }
/// }
/// renderer.render_by_line(FrameBuffer{ frame_buffer: the_frame_buffer, stride: display_width });
/// # }
/// ```
pub fn render_by_line(&self, line_buffer: impl LineBufferProvider) -> PhysicalRegion {
let Some(window) = self.maybe_window_adapter.borrow().as_ref().and_then(|w| w.upgrade())
else {
return Default::default();
};
let window_inner = WindowInner::from_pub(window.window());
let component_rc = window_inner.component();
let component = crate::item_tree::ItemTreeRc::borrow_pin(&component_rc);
if let Some(window_item) = crate::items::ItemRef::downcast_pin::<crate::items::WindowItem>(
component.as_ref().get_item_ref(0),
) {
let factor = ScaleFactor::new(window_inner.scale_factor());
let size = LogicalSize::from_lengths(window_item.width(), window_item.height()).cast()
* factor;
render_window_frame_by_line(
window_inner,
window_item.background(),
size.cast(),
self,
line_buffer,
)
} else {
PhysicalRegion { ..Default::default() }
}
}
}
#[doc(hidden)]
impl RendererSealed for SoftwareRenderer {
fn text_size(
&self,
font_request: crate::graphics::FontRequest,
text: &str,
max_width: Option<LogicalLength>,
scale_factor: ScaleFactor,
) -> LogicalSize {
fonts::text_size(font_request, text, max_width, scale_factor)
}
fn text_input_byte_offset_for_position(
&self,
text_input: Pin<&crate::items::TextInput>,
pos: LogicalPoint,
font_request: crate::graphics::FontRequest,
scale_factor: ScaleFactor,
) -> usize {
let visual_representation = text_input.visual_representation(None);
let font = fonts::match_font(&font_request, scale_factor);
let width = (text_input.width().cast() * scale_factor).cast();
let height = (text_input.height().cast() * scale_factor).cast();
let pos = (pos.cast() * scale_factor)
.clamp(euclid::point2(0., 0.), euclid::point2(i16::MAX, i16::MAX).cast())
.cast();
match font {
fonts::Font::PixelFont(pf) => {
let layout = fonts::text_layout_for_font(&pf, &font_request, scale_factor);
let paragraph = TextParagraphLayout {
string: &visual_representation.text,
layout,
max_width: width,
max_height: height,
horizontal_alignment: text_input.horizontal_alignment(),
vertical_alignment: text_input.vertical_alignment(),
wrap: text_input.wrap(),
overflow: TextOverflow::Clip,
single_line: false,
};
visual_representation.map_byte_offset_from_byte_offset_in_visual_text(
paragraph.byte_offset_for_position((pos.x_length(), pos.y_length())),
)
}
#[cfg(all(feature = "software-renderer-systemfonts", not(target_arch = "wasm32")))]
fonts::Font::VectorFont(vf) => {
let layout = fonts::text_layout_for_font(&vf, &font_request, scale_factor);
let paragraph = TextParagraphLayout {
string: &visual_representation.text,
layout,
max_width: width,
max_height: height,
horizontal_alignment: text_input.horizontal_alignment(),
vertical_alignment: text_input.vertical_alignment(),
wrap: text_input.wrap(),
overflow: TextOverflow::Clip,
single_line: false,
};
visual_representation.map_byte_offset_from_byte_offset_in_visual_text(
paragraph.byte_offset_for_position((pos.x_length(), pos.y_length())),
)
}
}
}
fn text_input_cursor_rect_for_byte_offset(
&self,
text_input: Pin<&crate::items::TextInput>,
byte_offset: usize,
font_request: crate::graphics::FontRequest,
scale_factor: ScaleFactor,
) -> LogicalRect {
let visual_representation = text_input.visual_representation(None);
let font = fonts::match_font(&font_request, scale_factor);
let width = (text_input.width().cast() * scale_factor).cast();
let height = (text_input.height().cast() * scale_factor).cast();
let (cursor_position, cursor_height) = match font {
fonts::Font::PixelFont(pf) => {
let layout = fonts::text_layout_for_font(&pf, &font_request, scale_factor);
let paragraph = TextParagraphLayout {
string: &visual_representation.text,
layout,
max_width: width,
max_height: height,
horizontal_alignment: text_input.horizontal_alignment(),
vertical_alignment: text_input.vertical_alignment(),
wrap: text_input.wrap(),
overflow: TextOverflow::Clip,
single_line: false,
};
(paragraph.cursor_pos_for_byte_offset(byte_offset), pf.height())
}
#[cfg(all(feature = "software-renderer-systemfonts", not(target_arch = "wasm32")))]
fonts::Font::VectorFont(vf) => {
let layout = fonts::text_layout_for_font(&vf, &font_request, scale_factor);
let paragraph = TextParagraphLayout {
string: &visual_representation.text,
layout,
max_width: width,
max_height: height,
horizontal_alignment: text_input.horizontal_alignment(),
vertical_alignment: text_input.vertical_alignment(),
wrap: text_input.wrap(),
overflow: TextOverflow::Clip,
single_line: false,
};
(paragraph.cursor_pos_for_byte_offset(byte_offset), vf.height())
}
};
(PhysicalRect::new(
PhysicalPoint::from_lengths(cursor_position.0, cursor_position.1),
PhysicalSize::from_lengths(
(text_input.text_cursor_width().cast() * scale_factor).cast(),
cursor_height,
),
)
.cast()
/ scale_factor)
.cast()
}
fn free_graphics_resources(
&self,
_component: crate::item_tree::ItemTreeRef,
items: &mut dyn Iterator<Item = Pin<crate::items::ItemRef<'_>>>,
) -> Result<(), crate::platform::PlatformError> {
for item in items {
item.cached_rendering_data_offset().release(&mut self.partial_cache.borrow_mut());
}
// We don't have a way to determine the screen region of the delete items, what's in the cache is relative. So
// as a last resort, refresh everything.
self.force_screen_refresh.set(true);
Ok(())
}
fn mark_dirty_region(&self, region: crate::item_rendering::DirtyRegion) {
self.force_dirty.replace_with(|r| r.union(®ion));
}
fn register_bitmap_font(&self, font_data: &'static crate::graphics::BitmapFont) {
fonts::register_bitmap_font(font_data);
}
#[cfg(all(feature = "software-renderer-systemfonts", not(target_arch = "wasm32")))]
fn register_font_from_memory(
&self,
data: &'static [u8],
) -> Result<(), Box<dyn std::error::Error>> {
self::fonts::systemfonts::register_font_from_memory(data)
}
#[cfg(all(feature = "software-renderer-systemfonts", not(target_arch = "wasm32")))]
fn register_font_from_path(
&self,
path: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
self::fonts::systemfonts::register_font_from_path(path)
}
fn default_font_size(&self) -> LogicalLength {
self::fonts::DEFAULT_FONT_SIZE
}
fn set_window_adapter(&self, window_adapter: &Rc<dyn WindowAdapter>) {
*self.maybe_window_adapter.borrow_mut() = Some(Rc::downgrade(window_adapter));
self.partial_cache.borrow_mut().clear();
}
}
fn render_window_frame_by_line(
window: &WindowInner,
background: Brush,
size: PhysicalSize,
renderer: &SoftwareRenderer,
mut line_buffer: impl LineBufferProvider,
) -> PhysicalRegion {
let mut scene = prepare_scene(window, size, renderer);
let to_draw_tr = scene.dirty_region.bounding_rect();
let mut background_color = TargetPixel::background();
// FIXME gradient
TargetPixel::blend(&mut background_color, background.color().into());
while scene.current_line < to_draw_tr.origin.y_length() + to_draw_tr.size.height_length() {
for r in &scene.current_line_ranges {
line_buffer.process_line(
scene.current_line.get() as usize,
r.start as usize..r.end as usize,
|line_buffer| {
let offset = r.start;
line_buffer.fill(background_color);
for span in scene.items[0..scene.current_items_index].iter().rev() {
debug_assert!(scene.current_line >= span.pos.y_length());
debug_assert!(
scene.current_line < span.pos.y_length() + span.size.height_length(),
);
if span.pos.x >= r.end {
continue;
}
let begin = r.start.max(span.pos.x);
let end = r.end.min(span.pos.x + span.size.width);
if begin >= end {
continue;
}
let extra_left_clip = begin - span.pos.x;
let extra_right_clip = span.pos.x + span.size.width - end;
let range_buffer =
&mut line_buffer[(begin - offset) as usize..(end - offset) as usize];
match span.command {
SceneCommand::Rectangle { color } => {
TargetPixel::blend_slice(range_buffer, color);
}
SceneCommand::Texture { texture_index } => {
let texture = &scene.vectors.textures[texture_index as usize];
draw_functions::draw_texture_line(
&PhysicalRect { origin: span.pos, size: span.size },
scene.current_line,
texture,
range_buffer,
extra_left_clip,
);
}
SceneCommand::SharedBuffer { shared_buffer_index } => {
let texture = scene.vectors.shared_buffers
[shared_buffer_index as usize]
.as_texture();
draw_functions::draw_texture_line(
&PhysicalRect { origin: span.pos, size: span.size },
scene.current_line,
&texture,
range_buffer,
extra_left_clip,
);
}
SceneCommand::RoundedRectangle { rectangle_index } => {
let rr =
&scene.vectors.rounded_rectangles[rectangle_index as usize];
draw_functions::draw_rounded_rectangle_line(
&PhysicalRect { origin: span.pos, size: span.size },
scene.current_line,
rr,
range_buffer,
extra_left_clip,
extra_right_clip,
);
}
SceneCommand::Gradient { gradient_index } => {
let g = &scene.vectors.gradients[gradient_index as usize];
draw_functions::draw_gradient_line(
&PhysicalRect { origin: span.pos, size: span.size },
scene.current_line,
g,
range_buffer,
extra_left_clip,
);
}
}
}
},
);
}
if scene.current_line < to_draw_tr.origin.y_length() + to_draw_tr.size.height_length() {
scene.next_line();
}
}
scene.dirty_region
}
#[derive(Default)]
struct SceneVectors {
textures: Vec<SceneTexture<'static>>,
rounded_rectangles: Vec<RoundedRectangle>,
shared_buffers: Vec<SharedBufferCommand>,
gradients: Vec<GradientCommand>,
}
struct Scene {
/// the next line to be processed
current_line: PhysicalLength,
/// The items are sorted like so:
/// - `items[future_items_index..]` are the items that have `y > current_line`.
/// They must be sorted by `y` (top to bottom), then by `z` (front to back)
/// - `items[..current_items_index]` are the items that overlap with the current_line,
/// sorted by z (front to back)
items: Vec<SceneItem>,
vectors: SceneVectors,
future_items_index: usize,
current_items_index: usize,
dirty_region: PhysicalRegion,
current_line_ranges: Vec<core::ops::Range<i16>>,
range_valid_until_line: PhysicalLength,
}
impl Scene {
pub fn new(
mut items: Vec<SceneItem>,
vectors: SceneVectors,
dirty_region: PhysicalRegion,
) -> Self {
let current_line =
dirty_region.iter_box().map(|x| x.min.y_length()).min().unwrap_or_default();
items.retain(|i| i.pos.y_length() + i.size.height_length() > current_line);
items.sort_unstable_by(compare_scene_item);
let current_items_index = items.partition_point(|i| i.pos.y_length() <= current_line);
items[..current_items_index].sort_unstable_by(|a, b| b.z.cmp(&a.z));
let mut r = Self {
items,
current_line,
current_items_index,
future_items_index: current_items_index,
vectors,
dirty_region,
current_line_ranges: Default::default(),
range_valid_until_line: Default::default(),
};
r.recompute_ranges();
debug_assert_eq!(r.current_line, r.dirty_region.bounding_rect().origin.y_length());
r
}
/// Updates `current_items_index` and `future_items_index` to match the invariant
pub fn next_line(&mut self) {
self.current_line += PhysicalLength::new(1);
let skipped = self.current_line >= self.range_valid_until_line && self.recompute_ranges();
// The items array is split in part:
// 1. [0..i] are the items that have already been processed, that are on this line
// 2. [j..current_items_index] are the items from the previous line that might still be
// valid on this line
// 3. [tmp1, tmp2] is a buffer where we swap items so we can make room for the items in [0..i]
// 4. [future_items_index..] are the items which might get processed now
// 5. [current_items_index..tmp1], [tmp2..future_items_index] and [i..j] is garbage
//
// At each step, we selecting the item with the higher z from the list 2 or 3 or 4 and take it from
// that list. Then we add it to the list [0..i] if it needs more processing. If needed,
// we move the first item from list 2. to list 3. to make some room
let (mut i, mut j, mut tmp1, mut tmp2) =
(0, 0, self.current_items_index, self.current_items_index);
if skipped {
// Merge sort doesn't work in that case.
while j < self.current_items_index {
let item = self.items[j];
if item.pos.y_length() + item.size.height_length() > self.current_line {
self.items[i] = item;
i += 1;
}
j += 1;