Commit c010b24c69

c010b24c6936488f7cfb557b52f0bf873e19c762

parent: 362a323a5b

Unregistered key

vaw <git@nlih.de> · 2026-09-04 23:26 UTC
committer: <noreply@github.com>

Use `SlicedProtocol` to render images that are partially off-screen (#667)

Layout: unified · split

Cargo.lock +57 −5
@@ -1020,6 +1020,7 @@ dependencies = [
1020 "itoa", 1020 "itoa",
1021 "rustversion", 1021 "rustversion",
1022 "ryu", 1022 "ryu",
1023 "serde",
1023 "static_assertions", 1024 "static_assertions",
1024] 1025]
1025 1026
@@ -1180,6 +1181,23 @@ version = "0.8.21"
1180source = "registry+https://github.com/rust-lang/crates.io-index" 1181source = "registry+https://github.com/rust-lang/crates.io-index"
1181checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" 1182checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
1182 1183
1184[[package]]
1185name = "crossterm"
1186version = "0.28.1"
1187source = "registry+https://github.com/rust-lang/crates.io-index"
1188checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
1189dependencies = [
1190 "bitflags 2.13.0",
1191 "crossterm_winapi",
1192 "mio",
1193 "parking_lot 0.12.5",
1194 "rustix 0.38.44",
1195 "serde",
1196 "signal-hook",
1197 "signal-hook-mio",
1198 "winapi",
1199]
1200
1183[[package]] 1201[[package]]
1184name = "crossterm" 1202name = "crossterm"
1185version = "0.29.0" 1203version = "0.29.0"
@@ -1193,6 +1211,7 @@ dependencies = [
1193 "mio", 1211 "mio",
1194 "parking_lot 0.12.5", 1212 "parking_lot 0.12.5",
1195 "rustix 1.1.4", 1213 "rustix 1.1.4",
1214 "serde",
1196 "signal-hook", 1215 "signal-hook",
1197 "signal-hook-mio", 1216 "signal-hook-mio",
1198 "winapi", 1217 "winapi",
@@ -3701,7 +3720,7 @@ dependencies = [
3701 "anymap2", 3720 "anymap2",
3702 "arboard", 3721 "arboard",
3703 "bitflags 2.13.0", 3722 "bitflags 2.13.0",
3704 "crossterm", 3723 "crossterm 0.29.0",
3705 "derive_more 2.1.1", 3724 "derive_more 2.1.1",
3706 "editor-types", 3725 "editor-types",
3707 "intervaltree", 3726 "intervaltree",
@@ -3722,7 +3741,7 @@ version = "0.0.26"
3722source = "registry+https://github.com/rust-lang/crates.io-index" 3741source = "registry+https://github.com/rust-lang/crates.io-index"
3723checksum = "a9070725ef25a76d7dd3431c5ee4d108780dfc42d097d194d397721843b8ac30" 3742checksum = "a9070725ef25a76d7dd3431c5ee4d108780dfc42d097d194d397721843b8ac30"
3724dependencies = [ 3743dependencies = [
3725 "crossterm", 3744 "crossterm 0.29.0",
3726 "intervaltree", 3745 "intervaltree",
3727 "libc", 3746 "libc",
3728 "modalkit", 3747 "modalkit",
@@ -3903,6 +3922,12 @@ dependencies = [
3903 "libc", 3922 "libc",
3904] 3923]
3905 3924
3925[[package]]
3926name = "numtoa"
3927version = "0.2.4"
3928source = "registry+https://github.com/rust-lang/crates.io-index"
3929checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"
3930
3906[[package]] 3931[[package]]
3907name = "oauth2" 3932name = "oauth2"
3908version = "5.0.0" 3933version = "5.0.0"
@@ -4826,6 +4851,7 @@ dependencies = [
4826 "ratatui-crossterm", 4851 "ratatui-crossterm",
4827 "ratatui-macros", 4852 "ratatui-macros",
4828 "ratatui-termina", 4853 "ratatui-termina",
4854 "ratatui-termion",
4829 "ratatui-termwiz", 4855 "ratatui-termwiz",
4830 "ratatui-widgets", 4856 "ratatui-widgets",
4831 "serde", 4857 "serde",
@@ -4860,16 +4886,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
4860checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" 4886checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0"
4861dependencies = [ 4887dependencies = [
4862 "cfg-if", 4888 "cfg-if",
4863 "crossterm", 4889 "crossterm 0.28.1",
4890 "crossterm 0.29.0",
4864 "instability", 4891 "instability",
4865 "ratatui-core", 4892 "ratatui-core",
4866] 4893]
4867 4894
4868[[package]] 4895[[package]]
4869name = "ratatui-image" 4896name = "ratatui-image"
4870version = "11.0.6" 4897version = "11.0.8"
4871source = "registry+https://github.com/rust-lang/crates.io-index" 4898source = "registry+https://github.com/rust-lang/crates.io-index"
4872checksum = "e000b7a22eae639460bc6ec8bb1cc689ecae5b0ed21935cd7d7dd52d38270c86" 4899checksum = "399baa06251282b0c1bbb5762848cf98a6b7b84f44af7f0daf3213ace16df4f0"
4873dependencies = [ 4900dependencies = [
4874 "base64-simd", 4901 "base64-simd",
4875 "icy_sixel", 4902 "icy_sixel",
@@ -4905,6 +4932,17 @@ dependencies = [
4905 "termina", 4932 "termina",
4906] 4933]
4907 4934
4935[[package]]
4936name = "ratatui-termion"
4937version = "0.1.2"
4938source = "registry+https://github.com/rust-lang/crates.io-index"
4939checksum = "87c732202fa5a71a9da0991013f0853e53f87048f45198e3a1ca3ee722accc2f"
4940dependencies = [
4941 "instability",
4942 "ratatui-core",
4943 "termion",
4944]
4945
4908[[package]] 4946[[package]]
4909name = "ratatui-termwiz" 4947name = "ratatui-termwiz"
4910version = "0.1.2" 4948version = "0.1.2"
@@ -6058,6 +6096,17 @@ dependencies = [
6058 "phf_codegen 0.11.3", 6096 "phf_codegen 0.11.3",
6059] 6097]
6060 6098
6099[[package]]
6100name = "termion"
6101version = "4.0.6"
6102source = "registry+https://github.com/rust-lang/crates.io-index"
6103checksum = "f44138a9ae08f0f502f24104d82517ef4da7330c35acd638f1f29d3cd5475ecb"
6104dependencies = [
6105 "libc",
6106 "numtoa",
6107 "serde",
6108]
6109
6061[[package]] 6110[[package]]
6062name = "termios" 6111name = "termios"
6063version = "0.3.3" 6112version = "0.3.3"
@@ -6092,6 +6141,7 @@ dependencies = [
6092 "pest", 6141 "pest",
6093 "pest_derive", 6142 "pest_derive",
6094 "phf 0.11.3", 6143 "phf 0.11.3",
6144 "serde",
6095 "sha2", 6145 "sha2",
6096 "signal-hook", 6146 "signal-hook",
6097 "siphasher", 6147 "siphasher",
@@ -7101,6 +7151,7 @@ checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7"
7101dependencies = [ 7151dependencies = [
7102 "getrandom 0.3.4", 7152 "getrandom 0.3.4",
7103 "mac_address", 7153 "mac_address",
7154 "serde",
7104 "sha2", 7155 "sha2",
7105 "thiserror 1.0.69", 7156 "thiserror 1.0.69",
7106 "uuid", 7157 "uuid",
@@ -7115,6 +7166,7 @@ dependencies = [
7115 "csscolorparser", 7166 "csscolorparser",
7116 "deltae", 7167 "deltae",
7117 "lazy_static 1.5.0", 7168 "lazy_static 1.5.0",
7169 "serde",
7118 "wezterm-dynamic", 7170 "wezterm-dynamic",
7119] 7171]
7120 7172
Cargo.toml +2 −2
@@ -54,7 +54,7 @@ mime_guess = "2.0.4"
54nom = "8.0" 54nom = "8.0"
55open = "5.0.0" 55open = "5.0.0"
56rand = "0.10" 56rand = "0.10"
57ratatui = "0.30.2" 57ratatui = { version = "0.30.2", features = ["serde"] }
58regex = "1.5" 58regex = "1.5"
59rpassword = "7.2" 59rpassword = "7.2"
60serde = "1.0" 60serde = "1.0"
@@ -107,7 +107,7 @@ version = "1.24.1"
107features = ["macros", "net", "rt-multi-thread", "sync", "time"] 107features = ["macros", "net", "rt-multi-thread", "sync", "time"]
108 108
109[dependencies.ratatui-image] 109[dependencies.ratatui-image]
110version = "11.0.6" 110version = "11.0.8"
111default-features = false 111default-features = false
112features = ["serde", "crossterm", "image-defaults"] 112features = ["serde", "crossterm", "image-defaults"]
113 113
src/config.rs +4 −15
@@ -17,6 +17,7 @@ use matrix_sdk::authentication::matrix::MatrixSession;
17use matrix_sdk::media::MediaRetentionPolicy; 17use matrix_sdk::media::MediaRetentionPolicy;
18use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; 18use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
20use ratatui::layout::Size;
20use ratatui::style::{Color, Modifier as StyleModifier, Style}; 21use ratatui::style::{Color, Modifier as StyleModifier, Style};
21use ratatui::text::Span; 22use ratatui::text::Span;
22use ratatui_image::FilterType; 23use ratatui_image::FilterType;
@@ -695,7 +696,7 @@ pub struct Notifications {
695pub struct ImagePreviewValues { 696pub struct ImagePreviewValues {
696 pub enabled: bool, 697 pub enabled: bool,
697 pub lazy_load: bool, 698 pub lazy_load: bool,
698 pub size: ImagePreviewSize, 699 pub size: Size,
699 pub protocol: ImagePreviewProtocolValues, 700 pub protocol: ImagePreviewProtocolValues,
700} 701}
701 702
@@ -703,7 +704,7 @@ pub struct ImagePreviewValues {
703pub struct ImagePreview { 704pub struct ImagePreview {
704 pub enabled: Option<bool>, 705 pub enabled: Option<bool>,
705 pub lazy_load: Option<bool>, 706 pub lazy_load: Option<bool>,
706 pub size: Option<ImagePreviewSize>, 707 pub size: Option<Size>,
707 pub protocol: Option<ImagePreviewProtocolValues>, 708 pub protocol: Option<ImagePreviewProtocolValues>,
708} 709}
709 710
@@ -712,24 +713,12 @@ impl ImagePreview {
712 ImagePreviewValues { 713 ImagePreviewValues {
713 enabled: self.enabled.unwrap_or(true), 714 enabled: self.enabled.unwrap_or(true),
714 lazy_load: self.lazy_load.unwrap_or(true), 715 lazy_load: self.lazy_load.unwrap_or(true),
715 size: self.size.unwrap_or_default(), 716 size: self.size.unwrap_or(Size { width: 66, height: 10 }),
716 protocol: self.protocol.unwrap_or_default(), 717 protocol: self.protocol.unwrap_or_default(),
717 } 718 }
718 } 719 }
719} 720}
720 721
721#[derive(Clone, Copy, Deserialize, Debug)]
722pub struct ImagePreviewSize {
723 pub width: usize,
724 pub height: usize,
725}
726
727impl Default for ImagePreviewSize {
728 fn default() -> Self {
729 ImagePreviewSize { width: 66, height: 10 }
730 }
731}
732
733#[derive(Clone, Debug, Deserialize, Default)] 722#[derive(Clone, Debug, Deserialize, Default)]
734pub struct ImagePreviewProtocolValues { 723pub struct ImagePreviewProtocolValues {
735 pub r#type: Option<ProtocolType>, 724 pub r#type: Option<ProtocolType>,
src/message/mod.rs +39 −20
@@ -17,7 +17,9 @@ use matrix_sdk::ruma::events::room::message::RoomMessageEventContentWithoutRelat
17use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent}; 17use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent};
18use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; 18use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent};
19use matrix_sdk::send_queue::SendHandle; 19use matrix_sdk::send_queue::SendHandle;
20use ratatui::layout::Size;
20use ratatui::style::Color; 21use ratatui::style::Color;
22use ratatui_image::sliced::SlicedProtocol;
21use unicode_width::UnicodeWidthStr; 23use unicode_width::UnicodeWidthStr;
22 24
23use matrix_sdk::ruma::{ 25use matrix_sdk::ruma::{
@@ -59,10 +61,8 @@ use ratatui::{
59 61
60use modalkit::editing::cursor::Cursor; 62use modalkit::editing::cursor::Cursor;
61use modalkit::prelude::*; 63use modalkit::prelude::*;
62use ratatui_image::protocol::Protocol;
63 64
64use crate::base::MessageEdits; 65use crate::base::MessageEdits;
65use crate::config::ImagePreviewSize;
66use crate::preview::{ImageStatus, PreviewKind, PreviewManager}; 66use crate::preview::{ImageStatus, PreviewKind, PreviewManager};
67use crate::{ 67use crate::{
68 base::RoomInfo, 68 base::RoomInfo,
@@ -80,7 +80,7 @@ pub use self::compose::{text_to_message, text_to_text_message_event_content};
80use self::state::{body_cow_state, html_state}; 80use self::state::{body_cow_state, html_state};
81pub use html::TreeGenState; 81pub use html::TreeGenState;
82 82
83type ProtocolPreview<'a> = (&'a Protocol, u16, u16); 83type ProtocolPreview<'a> = (&'a SlicedProtocol, u16, u16);
84 84
85/// The key used for uniquely identifying messages within a room and its threads. 85/// The key used for uniquely identifying messages within a room and its threads.
86/// 86///
@@ -184,17 +184,17 @@ fn hash_message_id(id: &MessageId) -> Option<usize> {
184fn placeholder_frame( 184fn placeholder_frame(
185 text: Option<&str>, 185 text: Option<&str>,
186 outer_width: usize, 186 outer_width: usize,
187 image_preview_size: &ImagePreviewSize, 187 image_preview_size: &Size,
188) -> Option<String> { 188) -> Option<String> {
189 let ImagePreviewSize { width, height } = image_preview_size; 189 let Size { width, height } = image_preview_size;
190 let width = usize::min(*width, outer_width); 190 let width = usize::min(*width as usize, outer_width);
191 if width < 2 || *height < 2 { 191 if width < 2 || *height < 2 {
192 return None; 192 return None;
193 } 193 }
194 let mut placeholder = "\u{230c}".to_string(); 194 let mut placeholder = "\u{230c}".to_string();
195 placeholder.push_str(&" ".repeat(width - 2)); 195 placeholder.push_str(&" ".repeat(width - 2));
196 placeholder.push('\u{230d}'); 196 placeholder.push('\u{230d}');
197 placeholder.push_str(&"\n".repeat((height - 1) / 2)); 197 placeholder.push_str(&"\n".repeat((*height as usize - 1) / 2));
198 198
199 if *height > 2 && 199 if *height > 2 &&
200 let Some(text) = text && 200 let Some(text) = text &&
@@ -204,7 +204,7 @@ fn placeholder_frame(
204 placeholder.push_str(text); 204 placeholder.push_str(text);
205 } 205 }
206 206
207 placeholder.push_str(&"\n".repeat(height / 2)); 207 placeholder.push_str(&"\n".repeat(*height as usize / 2));
208 placeholder.push('\u{230e}'); 208 placeholder.push('\u{230e}');
209 placeholder.push_str(&" ".repeat(width - 2)); 209 placeholder.push_str(&" ".repeat(width - 2));
210 placeholder.push_str("\u{230f}\n"); 210 placeholder.push_str("\u{230f}\n");
@@ -1053,6 +1053,25 @@ impl Message {
1053 1053
1054 !prev.timestamp.same_day(self.timestamp) 1054 !prev.timestamp.same_day(self.timestamp)
1055 } 1055 }
1056 pub fn message_column_width(
1057 viewctx: &ViewportContext<MessageCursor>,
1058 settings: &ApplicationSettings,
1059 ) -> usize {
1060 let width = viewctx.get_width();
1061 let user_gutter = settings.tunables.user_gutter_width;
1062
1063 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
1064 settings.tunables.read_receipt_display
1065 {
1066 width - user_gutter - TIME_GUTTER - READ_GUTTER
1067 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1068 width - user_gutter - TIME_GUTTER
1069 } else if user_gutter + MIN_MSG_LEN <= width {
1070 width - user_gutter
1071 } else {
1072 width.saturating_sub(2)
1073 }
1074 }
1056 1075
1057 fn get_render_format<'a>( 1076 fn get_render_format<'a>(
1058 &'a self, 1077 &'a self,
@@ -1215,7 +1234,7 @@ impl Message {
1215 style: Style, 1234 style: Style,
1216 settings: &'a ApplicationSettings, 1235 settings: &'a ApplicationSettings,
1217 previews: &'a PreviewManager, 1236 previews: &'a PreviewManager,
1218 ) -> (Text<'a>, Option<&'a Protocol>) { 1237 ) -> (Text<'a>, Option<&'a SlicedProtocol>) {
1219 let mut proto = None; 1238 let mut proto = None;
1220 let placeholder = match self 1239 let placeholder = match self
1221 .image_preview() 1240 .image_preview()
@@ -1230,7 +1249,7 @@ impl Message {
1230 }, 1249 },
1231 Some(ImageStatus::Loaded(backend)) => { 1250 Some(ImageStatus::Loaded(backend)) => {
1232 proto = Some(backend); 1251 proto = Some(backend);
1233 placeholder_frame(Some("No Space..."), width, &backend.size().into()) 1252 placeholder_frame(None, width, &backend.size())
1234 }, 1253 },
1235 Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")), 1254 Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")),
1236 }; 1255 };
@@ -1582,7 +1601,7 @@ pub mod tests {
1582 } 1601 }
1583 1602
1584 assert_eq!( 1603 assert_eq!(
1585 placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }), 1604 placeholder_frame(None, 4, &Size { width: 4, height: 4 }),
1586 pretty_frame_test( 1605 pretty_frame_test(
1587 r#" 1606 r#"
1588⌌ ⌍ 1607⌌ ⌍
@@ -1594,7 +1613,7 @@ pub mod tests {
1594 ); 1613 );
1595 1614
1596 assert_eq!( 1615 assert_eq!(
1597 placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }), 1616 placeholder_frame(None, 2, &Size { width: 4, height: 4 }),
1598 pretty_frame_test( 1617 pretty_frame_test(
1599 r#" 1618 r#"
1600⌌⌍ 1619⌌⌍
@@ -1604,12 +1623,12 @@ pub mod tests {
1604"# 1623"#
1605 ) 1624 )
1606 ); 1625 );
1607 assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }), None); 1626 assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), None);
1608 1627
1609 assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }), None); 1628 assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), None);
1610 1629
1611 assert_eq!( 1630 assert_eq!(
1612 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }), 1631 placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }),
1613 pretty_frame_test( 1632 pretty_frame_test(
1614 r#" 1633 r#"
1615⌌ ⌍ 1634⌌ ⌍
@@ -1620,7 +1639,7 @@ pub mod tests {
1620 ) 1639 )
1621 ); 1640 );
1622 assert_eq!( 1641 assert_eq!(
1623 placeholder_frame(Some("OK"), 6, &ImagePreviewSize { width: 6, height: 6 }), 1642 placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 6 }),
1624 pretty_frame_test( 1643 pretty_frame_test(
1625 r#" 1644 r#"
1626⌌ ⌍ 1645⌌ ⌍
@@ -1633,7 +1652,7 @@ pub mod tests {
1633 ) 1652 )
1634 ); 1653 );
1635 assert_eq!( 1654 assert_eq!(
1636 placeholder_frame(Some("OK"), 6, &ImagePreviewSize { width: 6, height: 7 }), 1655 placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 7 }),
1637 pretty_frame_test( 1656 pretty_frame_test(
1638 r#" 1657 r#"
1639⌌ ⌍ 1658⌌ ⌍
@@ -1647,7 +1666,7 @@ pub mod tests {
1647 ) 1666 )
1648 ); 1667 );
1649 assert_eq!( 1668 assert_eq!(
1650 placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize { width: 4, height: 4 }), 1669 placeholder_frame(Some("idontfit"), 4, &Size { width: 4, height: 4 }),
1651 pretty_frame_test( 1670 pretty_frame_test(
1652 r#" 1671 r#"
1653⌌ ⌍ 1672⌌ ⌍
@@ -1658,7 +1677,7 @@ pub mod tests {
1658 ) 1677 )
1659 ); 1678 );
1660 assert_eq!( 1679 assert_eq!(
1661 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }), 1680 placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 2 }),
1662 pretty_frame_test( 1681 pretty_frame_test(
1663 r#" 1682 r#"
1664⌌ ⌍ 1683⌌ ⌍
@@ -1667,7 +1686,7 @@ pub mod tests {
1667 ) 1686 )
1668 ); 1687 );
1669 assert_eq!( 1688 assert_eq!(
1670 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }), 1689 placeholder_frame(Some("OK"), 4, &Size { width: 2, height: 3 }),
1671 pretty_frame_test( 1690 pretty_frame_test(
1672 r#" 1691 r#"
1673⌌⌍ 1692⌌⌍
src/preview.rs +16 −46
@@ -5,20 +5,21 @@ use matrix_sdk::{
5 media::{MediaFormat, MediaRequestParameters, UniqueKey}, 5 media::{MediaFormat, MediaRequestParameters, UniqueKey},
6 ruma::events::room::MediaSource, 6 ruma::events::room::MediaSource,
7}; 7};
8use ratatui::layout::{Rect, Size}; 8use ratatui::layout::Size;
9use ratatui_image::{FilterType, Resize, picker::Picker, protocol::Protocol}; 9use ratatui_image::sliced::SlicedProtocol;
10use ratatui_image::{FilterType, Resize, picker::Picker};
10use tokio::sync::Semaphore; 11use tokio::sync::Semaphore;
11 12
12use crate::{ 13use crate::{
13 base::{AsyncProgramStore, IambError}, 14 base::{AsyncProgramStore, IambError},
14 config::{ApplicationSettings, ImagePreviewSize, ImagePreviewValues}, 15 config::{ApplicationSettings, ImagePreviewValues},
15 worker::Requester, 16 worker::Requester,
16}; 17};
17 18
18pub enum ImageStatus { 19pub enum ImageStatus {
19 Queued(ImagePreviewSize), 20 Queued(Size),
20 Downloading(ImagePreviewSize), 21 Downloading(Size),
21 Loaded(Protocol), 22 Loaded(SlicedProtocol),
22 Error(String), 23 Error(String),
23} 24}
24 25
@@ -29,10 +30,10 @@ pub enum PreviewKind {
29} 30}
30 31
31impl PreviewKind { 32impl PreviewKind {
32 fn image_size(self, image_preview: &ImagePreviewValues) -> ImagePreviewSize { 33 fn image_size(self, image_preview: &ImagePreviewValues) -> Size {
33 match self { 34 match self {
34 Self::Message => image_preview.size, 35 Self::Message => image_preview.size,
35 Self::Reaction => ImagePreviewSize { width: 2, height: 1 }, 36 Self::Reaction => Size { width: 2, height: 1 },
36 } 37 }
37 } 38 }
38} 39}
@@ -108,7 +109,6 @@ impl PreviewManager {
108 } 109 }
109} 110}
110 111
111#[cfg(not(windows))]
112fn picker_from_query() -> Picker { 112fn picker_from_query() -> Picker {
113 // XXX: documentation says to use this query on alternate screen but it seems to be fine 113 // XXX: documentation says to use this query on alternate screen but it seems to be fine
114 Picker::from_query_stdio().unwrap_or_else(|e| { 114 Picker::from_query_stdio().unwrap_or_else(|e| {
@@ -117,16 +117,11 @@ fn picker_from_query() -> Picker {
117 }) 117 })
118} 118}
119 119
120#[cfg(windows)]
121fn picker_from_query() -> Picker {
122 tracing::error!(
123 "\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows."
124 );
125 Picker::halfblocks()
126}
127
128fn picker_from_settings(settings: &ApplicationSettings) -> Picker { 120fn picker_from_settings(settings: &ApplicationSettings) -> Picker {
129 let mut picker = if let Some(font_size) = settings.tunables.image_preview.protocol.font_size { 121 let mut picker = if !settings.tunables.image_preview.enabled {
122 // Skip any auto-detection and use halfblocks when disabled:
123 Picker::halfblocks()
124 } else if let Some(font_size) = settings.tunables.image_preview.protocol.font_size {
130 #[expect(deprecated, reason = "from_query_stdio doesn't work on windows")] 125 #[expect(deprecated, reason = "from_query_stdio doesn't work on windows")]
131 Picker::from_fontsize(font_size.into()) 126 Picker::from_fontsize(font_size.into())
132 } else { 127 } else {
@@ -141,30 +136,6 @@ fn picker_from_settings(settings: &ApplicationSettings) -> Picker {
141 picker 136 picker
142} 137}
143 138
144impl From<ImagePreviewSize> for Rect {
145 fn from(value: ImagePreviewSize) -> Self {
146 Rect::new(0, 0, value.width as _, value.height as _)
147 }
148}
149
150impl From<ImagePreviewSize> for Size {
151 fn from(value: ImagePreviewSize) -> Self {
152 Size::new(value.width as _, value.height as _)
153 }
154}
155
156impl From<Rect> for ImagePreviewSize {
157 fn from(rect: Rect) -> Self {
158 ImagePreviewSize { width: rect.width as _, height: rect.height as _ }
159 }
160}
161
162impl From<Size> for ImagePreviewSize {
163 fn from(size: Size) -> Self {
164 ImagePreviewSize { width: size.width as _, height: size.height as _ }
165 }
166}
167
168pub async fn load_image( 139pub async fn load_image(
169 store: AsyncProgramStore, 140 store: AsyncProgramStore,
170 media: Media, 141 media: Media,
@@ -172,14 +143,14 @@ pub async fn load_image(
172 kind: PreviewKind, 143 kind: PreviewKind,
173 picker: Arc<Picker>, 144 picker: Arc<Picker>,
174 permits: Arc<Semaphore>, 145 permits: Arc<Semaphore>,
175 size: ImagePreviewSize, 146 size: Size,
176) { 147) {
177 async fn load_image_inner( 148 async fn load_image_inner(
178 media: Media, 149 media: Media,
179 source: MediaSource, 150 source: MediaSource,
180 picker: Arc<Picker>, 151 picker: Arc<Picker>,
181 permits: Arc<Semaphore>, 152 permits: Arc<Semaphore>,
182 size: ImagePreviewSize, 153 size: Size,
183 filter: FilterType, 154 filter: FilterType,
184 ) -> Result<ImageStatus, IambError> { 155 ) -> Result<ImageStatus, IambError> {
185 let reader = media 156 let reader = media
@@ -198,8 +169,7 @@ pub async fn load_image(
198 let handle = tokio::task::spawn_blocking(move || { 169 let handle = tokio::task::spawn_blocking(move || {
199 let image = reader.decode().map_err(IambError::Image)?; 170 let image = reader.decode().map_err(IambError::Image)?;
200 171
201 picker 172 SlicedProtocol::new_with_resize(&picker, image, size, Resize::Fit(Some(filter)))
202 .new_protocol(image, size.into(), Resize::Fit(Some(filter)))
203 .map_err(|err| IambError::Preview(err.to_string())) 173 .map_err(|err| IambError::Preview(err.to_string()))
204 }); 174 });
205 175
src/windows/room/scrollback.rs +42 −12
@@ -1,5 +1,5 @@
1//! Message scrollback 1//! Message scrollback
2use ratatui_image::Image; 2use ratatui_image::sliced::{SignedPosition, SlicedImage};
3use regex::Regex; 3use regex::Regex;
4 4
5use matrix_sdk::ruma::{OwnedEventId, OwnedRoomId}; 5use matrix_sdk::ruma::{OwnedEventId, OwnedRoomId};
@@ -1411,6 +1411,8 @@ impl StatefulWidget for Scrollback<'_> {
1411 } 1411 }
1412 1412
1413 let previews = &self.store.application.previews; 1413 let previews = &self.store.application.previews;
1414 let mut image_previews = vec![];
1415
1414 for (key, item) in thread.range(&corner_key..) { 1416 for (key, item) in thread.range(&corner_key..) {
1415 let sel = key == cursor_key; 1417 let sel = key == cursor_key;
1416 1418
@@ -1429,7 +1431,13 @@ impl StatefulWidget for Scrollback<'_> {
1429 } 1431 }
1430 1432
1431 if key == &corner_key && row < corner.text_row { 1433 if key == &corner_key && row < corner.text_row {
1432 // Skip rows above the viewport corner. 1434 // Skip rows above the viewport corner but keep image previews.
1435 let y = area.top() as i16 + row as i16 - corner.text_row as i16;
1436 let line_previews = msg_previews
1437 .extract_if(.., |(_, _, y)| *y as usize == row)
1438 .map(|(backend, msg_x, _)| (area.left() + msg_x, y, backend));
1439 image_previews.extend(line_previews);
1440
1433 continue; 1441 continue;
1434 } 1442 }
1435 1443
@@ -1446,7 +1454,16 @@ impl StatefulWidget for Scrollback<'_> {
1446 1454
1447 if lines.len() > height { 1455 if lines.len() > height {
1448 let n = lines.len() - height; 1456 let n = lines.len() - height;
1449 let _ = lines.drain(..n); 1457 let previews =
1458 lines
1459 .drain(..n)
1460 .zip(-(n as i16)..)
1461 .flat_map(|((_, _, _, line_previews, _), y)| {
1462 line_previews.into_iter().map(move |(backend, msg_x, _)| {
1463 (area.left() + msg_x, area.top() as i16 + y, backend)
1464 })
1465 });
1466 image_previews.extend(previews);
1450 } 1467 }
1451 1468
1452 if let Some((key, row, _, _, _)) = lines.first() { 1469 if let Some((key, row, _, _, _)) = lines.first() {
@@ -1457,11 +1474,12 @@ impl StatefulWidget for Scrollback<'_> {
1457 let mut y = area.top(); 1474 let mut y = area.top();
1458 let x = area.left(); 1475 let x = area.left();
1459 1476
1460 let mut image_previews = vec![];
1461 for (key, row, txt, line_preview, includes_date_line) in lines.into_iter() { 1477 for (key, row, txt, line_preview, includes_date_line) in lines.into_iter() {
1462 let _ = buf.set_line(x, y, &txt, area.width); 1478 let _ = buf.set_line(x, y, &txt, area.width);
1463 image_previews.extend( 1479 image_previews.extend(
1464 line_preview.into_iter().map(|(backend, msg_x, _)| (x + msg_x, y, backend)), 1480 line_preview
1481 .into_iter()
1482 .map(|(backend, msg_x, _)| (x + msg_x, y as i16, backend)),
1465 ); 1483 );
1466 1484
1467 if key == cursor_key && row == usize::from(includes_date_line) { 1485 if key == cursor_key && row == usize::from(includes_date_line) {
@@ -1470,16 +1488,28 @@ impl StatefulWidget for Scrollback<'_> {
1470 1488
1471 y += 1; 1489 y += 1;
1472 } 1490 }
1491
1492 let msg_width = Message::message_column_width(&state.viewctx, settings);
1493
1473 // Render image previews after all text lines have been drawn, as the render might draw below the current 1494 // Render image previews after all text lines have been drawn, as the render might draw below the current
1474 // line. 1495 // line.
1475 for (x, y, backend) in image_previews { 1496 for (x, y, backend) in image_previews {
1476 let image_widget = Image::new(backend); 1497 if backend.size().height as i16 + y >= area.y as i16 {
1477 let mut rect: Rect = backend.size().into(); 1498 let hidden_lines = (area.y as i16 - y).max(0);
1478 rect.x = x; 1499
1479 rect.y = y; 1500 let position = SignedPosition { x: 0, y: -hidden_lines };
1480 // Don't render outside of scrollback area 1501 let image_widget = SlicedImage::new(backend, position);
1481 if rect.bottom() <= area.bottom() && rect.right() <= area.right() { 1502 let mut rect: Rect = backend.size().into();
1482 image_widget.render(rect, buf); 1503 rect.x = x;
1504 rect.y = (y + hidden_lines) as u16;
1505
1506 rect.height -= hidden_lines as u16;
1507 rect.width = rect.width.min(msg_width as u16);
1508
1509 let rect = rect.intersection(area);
1510 if !rect.is_empty() {
1511 image_widget.render(rect, buf);
1512 }
1483 } 1513 }
1484 } 1514 }
1485 1515
src/worker.rs +4 −3
@@ -18,6 +18,7 @@ use matrix_sdk::ruma::events::key::verification::ready::{
18 ToDeviceKeyVerificationReadyEvent, 18 ToDeviceKeyVerificationReadyEvent,
19}; 19};
20use matrix_sdk_base::RoomStateFilter; 20use matrix_sdk_base::RoomStateFilter;
21use ratatui::layout::Size;
21use ratatui_image::picker::Picker; 22use ratatui_image::picker::Picker;
22use tokio::sync::Semaphore; 23use tokio::sync::Semaphore;
23use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; 24use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
@@ -92,7 +93,7 @@ use modalkit::errors::UIError;
92use modalkit::prelude::{EditInfo, InfoMessage}; 93use modalkit::prelude::{EditInfo, InfoMessage};
93 94
94use crate::base::{EchoLocation, MessageNeed}; 95use crate::base::{EchoLocation, MessageNeed};
95use crate::config::{ImagePreviewSize, ProxyUrl}; 96use crate::config::ProxyUrl;
96use crate::message::{Message, MessageEvent, MessageId, MessageKey}; 97use crate::message::{Message, MessageEvent, MessageId, MessageKey};
97use crate::notifications::register_notifications; 98use crate::notifications::register_notifications;
98use crate::preview::PreviewKind; 99use crate::preview::PreviewKind;
@@ -736,7 +737,7 @@ pub enum WorkerTask {
736 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>), 737 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
737 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>), 738 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
738 TypingNotice(OwnedRoomId), 739 TypingNotice(OwnedRoomId),
739 LoadImage(MediaSource, PreviewKind, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>), 740 LoadImage(MediaSource, PreviewKind, Size, Arc<Picker>, Arc<Semaphore>),
740} 741}
741 742
742impl Debug for WorkerTask { 743impl Debug for WorkerTask {
@@ -970,7 +971,7 @@ impl Requester {
970 &self, 971 &self,
971 source: MediaSource, 972 source: MediaSource,
972 kind: PreviewKind, 973 kind: PreviewKind,
973 size: ImagePreviewSize, 974 size: Size,
974 picker: Arc<Picker>, 975 picker: Arc<Picker>,
975 permits: Arc<Semaphore>, 976 permits: Arc<Semaphore>,
976 ) { 977 ) {