xref: /aosp_15_r20/external/crosvm/gpu_display/examples/simple_open.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 // Copyright 2022 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::process::exit;
6 
7 use anyhow::Context;
8 use anyhow::Result;
9 use gpu_display::GpuDisplay;
10 use gpu_display::SurfaceType;
11 use vm_control::gpu::DisplayMode;
12 use vm_control::gpu::DisplayParameters;
13 
run() -> Result<()>14 fn run() -> Result<()> {
15     let mut disp = GpuDisplay::open_x(None::<&str>).context("open_x")?;
16     let surface_id = disp
17         .create_surface(
18             None,
19             /* scanout_id= */ Some(0),
20             &DisplayParameters::default_with_mode(DisplayMode::Windowed(1280, 1024)),
21             SurfaceType::Scanout,
22         )
23         .context("create_surface")?;
24 
25     let mem = disp.framebuffer(surface_id).context("framebuffer")?;
26     for y in 0..1024 {
27         let mut row = [0u32; 1280];
28         for (x, item) in row.iter_mut().enumerate() {
29             let b = ((x as f32 / 1280.0) * 256.0) as u32;
30             let g = ((y as f32 / 1024.0) * 256.0) as u32;
31             *item = b | (g << 8);
32         }
33         mem.as_volatile_slice()
34             .offset(1280 * 4 * y)
35             .unwrap()
36             .copy_from(&row);
37     }
38     disp.flip(surface_id);
39 
40     while !disp.close_requested(surface_id) {
41         disp.dispatch_events().context("dispatch_events")?;
42     }
43 
44     Ok(())
45 }
46 
main()47 fn main() {
48     if let Err(e) = run() {
49         eprintln!("error: {:#}", e);
50         exit(1);
51     }
52 }
53