xref: /aosp_15_r20/frameworks/native/libs/nativewindow/rust/src/surface/buffer.rs (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 // Copyright (C) 2024 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use super::{ErrorCode, Surface};
16 use nativewindow_bindgen::{AHardwareBuffer_Format, ANativeWindow_Buffer};
17 use std::ptr::null_mut;
18 
19 /// An empty `ANativeWindow_Buffer`.
20 pub const EMPTY: ANativeWindow_Buffer = ANativeWindow_Buffer {
21     width: 0,
22     height: 0,
23     stride: 0,
24     format: 0,
25     bits: null_mut(),
26     reserved: [0; 6],
27 };
28 
29 /// Rust wrapper for `ANativeWindow_Buffer`, representing a locked buffer from a [`Surface`].
30 pub struct Buffer<'a> {
31     /// The wrapped `ANativeWindow_Buffer`.
32     pub buffer: ANativeWindow_Buffer,
33     surface: &'a mut Surface,
34 }
35 
36 impl<'a> Buffer<'a> {
new(buffer: ANativeWindow_Buffer, surface: &'a mut Surface) -> Self37     pub(crate) fn new(buffer: ANativeWindow_Buffer, surface: &'a mut Surface) -> Self {
38         Self { buffer, surface }
39     }
40 
41     /// Unlocks the window's drawing surface which was previously locked to create this buffer,
42     /// posting the buffer to the display.
unlock_and_post(self) -> Result<(), ErrorCode>43     pub fn unlock_and_post(self) -> Result<(), ErrorCode> {
44         self.surface.unlock_and_post()
45     }
46 
47     /// The number of pixels that are shown horizontally.
width(&self) -> i3248     pub fn width(&self) -> i32 {
49         self.buffer.width
50     }
51 
52     /// The number of pixels that are shown vertically.
height(&self) -> i3253     pub fn height(&self) -> i32 {
54         self.buffer.height
55     }
56 
57     /// The number of pixels that a line in the buffer takes in memory.
58     ///
59     /// This may be greater than the width.
stride(&self) -> i3260     pub fn stride(&self) -> i32 {
61         self.buffer.stride
62     }
63 
64     /// The pixel format of the buffer.
format(&self) -> Result<AHardwareBuffer_Format::Type, ErrorCode>65     pub fn format(&self) -> Result<AHardwareBuffer_Format::Type, ErrorCode> {
66         self.buffer.format.try_into().map_err(|_| ErrorCode(self.buffer.format))
67     }
68 }
69