Fix crash on small image preview (#198)

This commit is contained in:
Benjamin Grosse 2024-01-28 07:35:07 +00:00 committed by GitHub
parent 999399a70f
commit 88af9bfec3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -841,10 +841,10 @@ impl Message {
if let Some(placeholder) = match &self.image_preview {
ImageStatus::None => None,
ImageStatus::Downloading(image_preview_size) => {
Some(Message::placeholder_frame(Some("Downloading..."), image_preview_size))
Message::placeholder_frame(Some("Downloading..."), width, image_preview_size)
},
ImageStatus::Loaded(backend) => {
Some(Message::placeholder_frame(None, &backend.rect().into()))
Message::placeholder_frame(None, width, &backend.rect().into())
},
ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")),
} {
@ -864,21 +864,32 @@ impl Message {
}
/// Before the image is loaded, already display a placeholder frame of the image size.
fn placeholder_frame(text: Option<&str>, image_preview_size: &ImagePreviewSize) -> String {
fn placeholder_frame(
text: Option<&str>,
outer_width: usize,
image_preview_size: &ImagePreviewSize,
) -> Option<String> {
let ImagePreviewSize { width, height } = image_preview_size;
if outer_width < *width || (*width < 2 || *height < 2) {
return None;
}
let mut placeholder = "\u{230c}".to_string();
placeholder.push_str(&" ".repeat(width - 2));
placeholder.push_str("\u{230d}\n");
placeholder.push(' ');
if *height > 2 {
if let Some(text) = text {
if text.width() <= width - 2 {
placeholder.push(' ');
placeholder.push_str(text);
}
}
}
placeholder.push_str(&"\n".repeat(height - 2));
placeholder.push('\u{230e}');
placeholder.push_str(&" ".repeat(width - 2));
placeholder.push_str("\u{230f}\n");
placeholder
Some(placeholder)
}
fn show_sender<'a>(
@ -1122,4 +1133,82 @@ pub mod tests {
"<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
);
}
#[test]
fn test_placeholder_frame() {
fn pretty_frame_test(str: &str) -> Option<String> {
Some(str[1..].to_string())
}
assert_eq!(
Message::placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }),
pretty_frame_test(
r#"
"#
)
);
assert_eq!(
Message::placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }),
None
);
assert_eq!(
Message::placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }),
None
);
assert_eq!(
Message::placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }),
None
);
assert_eq!(
Message::placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }),
pretty_frame_test(
r#"
OK
"#
)
);
assert_eq!(
Message::placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize {
width: 4,
height: 4,
}),
pretty_frame_test(
r#"
"#
)
);
assert_eq!(
Message::placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }),
pretty_frame_test(
r#"
"#
)
);
assert_eq!(
Message::placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }),
pretty_frame_test(
r#"
"#
)
);
}
}