crabshell_render/
capture.rs1use std::rc::Rc;
6
7use crabshell_ui::{CaptureFrame, Fit};
8use tiny_skia::PixmapRef;
9
10use crate::PixelFormat;
11use crate::icons::halve;
12use crate::images;
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub struct Turn {
19 pub quarters: u8,
21 pub flipped: bool,
23}
24
25impl Turn {
26 fn sideways(self) -> bool {
28 self.quarters % 2 == 1
29 }
30}
31
32pub fn capture_frame(
40 pixels: &[u8],
41 width: u32,
42 height: u32,
43 format: PixelFormat,
44 opaque: bool,
45 turn: Turn,
46 cover: (u32, u32),
47) -> Option<CaptureFrame> {
48 let source = PixmapRef::from_bytes(pixels, width, height)?;
49 let cover = if turn.sideways() {
51 (cover.1, cover.0)
52 } else {
53 cover
54 };
55 let (kept_width, kept_height) = frame_size((width, height), cover);
56 let mut first = if kept_width * 2 <= width && kept_height * 2 <= height {
59 halve(source).ok()?
60 } else {
61 source.to_owned()
62 };
63 if opaque {
64 for pixel in first.data_mut().as_chunks_mut::<4>().0 {
65 pixel[3] = 255;
66 }
67 }
68 let mut kept = if (first.width(), first.height()) == (kept_width, kept_height) {
71 first
72 } else {
73 images::scale(first.as_ref(), kept_width, kept_height, Fit::Fill).ok()?
74 };
75 if format == PixelFormat::Argb8888 {
76 for pixel in kept.data_mut().as_chunks_mut::<4>().0 {
77 pixel.swap(0, 2);
78 }
79 }
80 let (logical_width, logical_height) = match turn.sideways() {
81 true => (height, width),
82 false => (width, height),
83 };
84 let (width, height, rgba) = upright(kept_width, kept_height, kept.take(), turn);
85 Some(CaptureFrame {
86 width,
87 height,
88 logical_width,
89 logical_height,
90 rgba: Rc::from(rgba),
91 })
92}
93
94fn upright(width: u32, height: u32, rgba: Vec<u8>, turn: Turn) -> (u32, u32, Vec<u8>) {
96 if turn == Turn::default() {
97 return (width, height, rgba);
98 }
99 let (w, h) = (width as usize, height as usize);
100 let (out_w, out_h) = if turn.sideways() { (h, w) } else { (w, h) };
101 let mut out = vec![0; rgba.len()];
102 for y in 0..out_h {
103 for x in 0..out_w {
104 let (bx, by) = match turn.quarters % 4 {
108 0 => (x, y),
109 1 => (y, h - 1 - x),
110 2 => (w - 1 - x, h - 1 - y),
111 _ => (w - 1 - y, x),
112 };
113 let bx = if turn.flipped { w - 1 - bx } else { bx };
114 let (from, to) = ((by * w + bx) * 4, (y * out_w + x) * 4);
115 out[to..to + 4].copy_from_slice(&rgba[from..from + 4]);
116 }
117 }
118 (out_w as u32, out_h as u32, out)
119}
120
121pub fn frame_size(source: (u32, u32), cover: (u32, u32)) -> (u32, u32) {
126 let across = f64::from(cover.0) / f64::from(source.0.max(1));
127 let down = f64::from(cover.1) / f64::from(source.1.max(1));
128 let factor = across.max(down).min(1.0);
129 let side = |length: u32| ((f64::from(length) * factor).round() as u32).max(1);
131 (side(source.0), side(source.1))
132}