File: utils.rs

package info (click to toggle)
glycin 1.2.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 11,868 kB
  • sloc: python: 257; ansic: 93; xml: 44; makefile: 28; sh: 21; javascript: 10
file content (172 lines) | stat: -rw-r--r-- 4,847 bytes parent folder | download
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
#![allow(dead_code)]

use std::ffi::OsString;
use std::path::{Path, PathBuf};

use gdk::prelude::*;
use tracing_subscriber::prelude::*;

pub fn init() {
    let _ = tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::from_default_env())
        .with(tracing_subscriber::fmt::Layer::default().compact())
        .try_init();
}

pub fn reference_image_path(dir: impl AsRef<Path>, frame: Option<u64>) -> PathBuf {
    let mut path = dir.as_ref().to_path_buf();
    if let Some(frame) = frame {
        let mut name = path.file_name().unwrap().to_owned();
        name.push(format!("-{frame}"));
        path.set_file_name(name);
    }
    path.set_extension("png");
    path
}

pub fn skip_file(path: &Path) -> bool {
    extensions_to_skip().contains(&path.extension().unwrap_or_default().into())
}

pub fn extensions_to_skip() -> Vec<OsString> {
    option_env!("GLYCIN_TEST_SKIP_EXT")
        .unwrap_or_default()
        .split(|x| x == ',')
        .map(OsString::from)
        .collect()
}

pub async fn compare_images_path(
    reference_path: impl AsRef<Path>,
    path_compare: impl AsRef<Path>,
    exif: bool,
) -> TestResult {
    let data = get_downloaded_texture(&path_compare).await;
    compare_images(&reference_path, &path_compare, &data, exif).await
}

#[cfg(not(feature = "tokio"))]
pub fn block_on<F: std::future::Future>(future: F) -> F::Output {
    async_io::block_on(future)
}

#[cfg(feature = "tokio")]
pub fn block_on<F: std::future::Future>(future: F) -> F::Output {
    use std::sync::OnceLock;
    static TOKIO_RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
    let runtime =
        TOKIO_RT.get_or_init(|| tokio::runtime::Runtime::new().expect("tokio runtime was created"));
    runtime.block_on(future)
}

async fn get_downloaded_texture(path: impl AsRef<Path>) -> Vec<u8> {
    let texture = get_texture(&path).await;
    texture_to_bytes(&texture)
}

pub fn texture_to_bytes(texture: &gdk::Texture) -> Vec<u8> {
    let mut data = vec![0; texture.width() as usize * texture.height() as usize * 4];
    texture.download(&mut data, texture.width() as usize * 4);
    data
}

async fn debug_file(path: impl AsRef<Path>) {
    let texture = get_texture(&path).await;
    let mut new_path = PathBuf::from("failures");
    new_path.push(path.as_ref().file_name().unwrap());
    let mut extension = new_path.extension().unwrap().to_os_string();
    extension.push(".png");
    new_path.set_extension(extension);
    texture.save_to_png(new_path).unwrap();
}

async fn get_texture(path: impl AsRef<Path>) -> gdk::Texture {
    let file = gio::File::for_path(&path);
    let image_request = glycin::Loader::new(file);
    let image = image_request.load().await.unwrap();
    let frame = image.next_frame().await.unwrap();
    frame.texture()
}

async fn get_info(path: impl AsRef<Path>) -> glycin::ImageInfo {
    let file = gio::File::for_path(&path);
    let image_request = glycin::Loader::new(file);
    let image = image_request.load().await.unwrap();
    image.info().clone()
}

pub async fn compare_images(
    reference_path: impl AsRef<Path>,
    path: impl AsRef<Path>,
    data: &[u8],
    test_exif: bool,
) -> TestResult {
    let reference_data = get_downloaded_texture(&reference_path).await;

    assert_eq!(reference_data.len(), data.len());

    let len = data.len();

    let mut dev = 0;
    for (r, p) in reference_data.into_iter().zip(data) {
        dev += (r as i16 - *p as i16).unsigned_abs() as u64;
    }

    let texture_deviation = dev as f64 / len as f64;

    let texture_eq = texture_deviation < 3.1;

    if !texture_eq {
        debug_file(&path).await;
    }

    let reference_exif = get_info(&reference_path)
        .await
        .details
        .exif
        .map(|x| x.get().unwrap());
    let exif = get_info(&path).await.details.exif.map(|x| x.get().unwrap());

    let exif_eq = if !test_exif
        || (reference_exif.is_none() && path.as_ref().extension().unwrap() == "tiff")
    {
        true
    } else {
        reference_exif.as_ref().map(|x| &x[..2]) == exif.as_ref().map(|x| &x[..2])
    };

    TestResult {
        path: path.as_ref().to_path_buf(),
        texture_eq,
        texture_deviation,
        exif_eq,
    }
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct TestResult {
    pub path: PathBuf,
    pub texture_eq: bool,
    pub texture_deviation: f64,
    pub exif_eq: bool,
}

impl TestResult {
    pub fn is_failed(&self) -> bool {
        !self.texture_eq || !self.exif_eq
    }

    pub fn check_multiple(results: Vec<Self>) {
        let mut some_failed = false;
        for result in results.iter() {
            if result.is_failed() {
                some_failed = true;
            } else {
                eprintln!("    (OK)");
            }
        }

        assert!(!some_failed, "{results:#?}");
    }
}