Commit 972ae5971d
Unregistered key
Layout: unified · split
docs/iamb.5 +7 −6
| @@ -142,6 +142,13 @@ Enable image previews and configure it. | |||
| 142 | An empty object will enable the feature with default settings, omitting it will disable the feature. | 142 | An empty object will enable the feature with default settings, omitting it will disable the feature. |
| 143 | The available fields in this object are: | 143 | The available fields in this object are: |
| 144 | .Bl -tag -width Ds | 144 | .Bl -tag -width Ds |
| 145 | .It Sy lazy_load | ||
| 146 | If | ||
| 147 | .Sy true | ||
| 148 | (the default), download and render image previews when viewing a message with an image. | ||
| 149 | If | ||
| 150 | .Sy false , | ||
| 151 | load previews as soon as a message with an image is received. | ||
| 145 | .It Sy size | 152 | .It Sy size |
| 146 | An optional object with | 153 | An optional object with |
| 147 | .Sy width | 154 | .Sy width |
| @@ -602,8 +609,6 @@ Configured as an object under the key | |||
| 602 | .It Sy cache | 609 | .It Sy cache |
| 603 | Specifies where to store assets and temporary data in. | 610 | Specifies where to store assets and temporary data in. |
| 604 | (For example, | 611 | (For example, |
| 605 | .Sy image_preview | ||
| 606 | and | ||
| 607 | .Sy logs | 612 | .Sy logs |
| 608 | will also go in here by default.) | 613 | will also go in here by default.) |
| 609 | Defaults to | 614 | Defaults to |
| @@ -616,10 +621,6 @@ Defaults to | |||
| 616 | Specifies where to store downloaded files. | 621 | Specifies where to store downloaded files. |
| 617 | Defaults to | 622 | Defaults to |
| 618 | .Ev $XDG_DOWNLOAD_DIR . | 623 | .Ev $XDG_DOWNLOAD_DIR . |
| 619 | .It Sy image_previews | ||
| 620 | Specifies where to store automatically downloaded image previews. | ||
| 621 | Defaults to | ||
| 622 | .Ev ${cache}/image_preview_downloads . | ||
| 623 | .It Sy logs | 624 | .It Sy logs |
| 624 | Specifies where to store log files. | 625 | Specifies where to store log files. |
| 625 | Defaults to | 626 | Defaults to |
src/base.rs +22 −41
| @@ -12,7 +12,9 @@ use std::sync::Arc; | |||
| 12 | use std::time::{Duration, Instant}; | 12 | use std::time::{Duration, Instant}; |
| 13 | 13 | ||
| 14 | use emojis::Emoji; | 14 | use emojis::Emoji; |
| 15 | |||
| 15 | use matrix_sdk::ruma::events::receipt::ReceiptThread; | 16 | use matrix_sdk::ruma::events::receipt::ReceiptThread; |
| 17 | use matrix_sdk::ruma::events::room::MediaSource; | ||
| 16 | use matrix_sdk::ruma::events::sticker::StickerEvent; | 18 | use matrix_sdk::ruma::events::sticker::StickerEvent; |
| 17 | use ratatui::{ | 19 | use ratatui::{ |
| 18 | buffer::Buffer, | 20 | buffer::Buffer, |
| @@ -91,9 +93,8 @@ use modalkit::{ | |||
| 91 | }; | 93 | }; |
| 92 | 94 | ||
| 93 | use crate::config::ImagePreviewProtocolValues; | 95 | use crate::config::ImagePreviewProtocolValues; |
| 94 | use crate::message::ImageStatus; | ||
| 95 | use crate::notifications::NotificationHandle; | 96 | use crate::notifications::NotificationHandle; |
| 96 | use crate::preview::{source_from_event, spawn_insert_preview}; | 97 | use crate::preview::{source_from_event, PreviewManager}; |
| 97 | use crate::{ | 98 | use crate::{ |
| 98 | message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}, | 99 | message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}, |
| 99 | worker::Requester, | 100 | worker::Requester, |
| @@ -1188,12 +1189,10 @@ impl RoomInfo { | |||
| 1188 | /// Insert a sticker | 1189 | /// Insert a sticker |
| 1189 | pub fn insert_sticker( | 1190 | pub fn insert_sticker( |
| 1190 | &mut self, | 1191 | &mut self, |
| 1191 | room_id: OwnedRoomId, | ||
| 1192 | store: AsyncProgramStore, | ||
| 1193 | picker: Option<Picker>, | ||
| 1194 | sticker: StickerEvent, | 1192 | sticker: StickerEvent, |
| 1195 | settings: &ApplicationSettings, | 1193 | settings: &ApplicationSettings, |
| 1196 | media: matrix_sdk::Media, | 1194 | previews: &mut PreviewManager, |
| 1195 | worker: &Requester, | ||
| 1197 | ) { | 1196 | ) { |
| 1198 | match sticker { | 1197 | match sticker { |
| 1199 | MessageLikeEvent::Original(ref sticker_content) => { | 1198 | MessageLikeEvent::Original(ref sticker_content) => { |
| @@ -1205,21 +1204,13 @@ impl RoomInfo { | |||
| 1205 | self.keys.insert(sticker_content.event_id.clone(), loc); | 1204 | self.keys.insert(sticker_content.event_id.clone(), loc); |
| 1206 | self.messages.insert_message(key.clone(), sticker.clone()); | 1205 | self.messages.insert_message(key.clone(), sticker.clone()); |
| 1207 | 1206 | ||
| 1208 | if picker.is_some() { | 1207 | if let (Some(msg), Some(image_preview)) = ( |
| 1209 | if let (Some(msg), Some(image_preview)) = ( | 1208 | self.get_event_mut(&sticker_content.event_id), |
| 1210 | self.get_event_mut(&sticker_content.event_id), | 1209 | &settings.tunables.image_preview, |
| 1211 | &settings.tunables.image_preview, | 1210 | ) { |
| 1212 | ) { | 1211 | let source: MediaSource = sticker_content.content.source.clone().into(); |
| 1213 | msg.image_preview = ImageStatus::Downloading(image_preview.size.clone()); | 1212 | msg.image_preview = Some(source.clone()); |
| 1214 | spawn_insert_preview( | 1213 | previews.register_preview(settings, source, image_preview.size, worker); |
| 1215 | store, | ||
| 1216 | room_id, | ||
| 1217 | sticker_content.event_id.clone(), | ||
| 1218 | sticker_content.content.source.clone().into(), | ||
| 1219 | media, | ||
| 1220 | settings.dirs.image_previews.clone(), | ||
| 1221 | ) | ||
| 1222 | } | ||
| 1223 | } | 1214 | } |
| 1224 | }, | 1215 | }, |
| 1225 | MessageLikeEvent::Redacted(ref redaction) => { | 1216 | MessageLikeEvent::Redacted(ref redaction) => { |
| @@ -1382,33 +1373,23 @@ impl RoomInfo { | |||
| 1382 | } | 1373 | } |
| 1383 | } | 1374 | } |
| 1384 | 1375 | ||
| 1385 | /// Insert a new message event, and spawn a task for image-preview if it has an image | 1376 | /// Insert a new message event, and prepare for image-preview if it has an image attachment. |
| 1386 | /// attachment. | ||
| 1387 | pub fn insert_with_preview( | 1377 | pub fn insert_with_preview( |
| 1388 | &mut self, | 1378 | &mut self, |
| 1389 | room_id: OwnedRoomId, | ||
| 1390 | store: AsyncProgramStore, | ||
| 1391 | picker: Option<Picker>, | ||
| 1392 | ev: RoomMessageEvent, | 1379 | ev: RoomMessageEvent, |
| 1393 | settings: &mut ApplicationSettings, | 1380 | settings: &ApplicationSettings, |
| 1394 | media: matrix_sdk::Media, | 1381 | previews: &mut PreviewManager, |
| 1382 | worker: &Requester, | ||
| 1395 | ) { | 1383 | ) { |
| 1396 | let source = picker.and_then(|_| source_from_event(&ev)); | 1384 | let source = source_from_event(&ev); |
| 1397 | self.insert(ev); | 1385 | self.insert(ev); |
| 1398 | 1386 | ||
| 1399 | if let Some((event_id, source)) = source { | 1387 | if let Some((event_id, source)) = source { |
| 1400 | if let (Some(msg), Some(image_preview)) = | 1388 | if let (Some(msg), Some(image_preview)) = |
| 1401 | (self.get_event_mut(&event_id), &settings.tunables.image_preview) | 1389 | (self.get_event_mut(&event_id), &settings.tunables.image_preview) |
| 1402 | { | 1390 | { |
| 1403 | msg.image_preview = ImageStatus::Downloading(image_preview.size.clone()); | 1391 | msg.image_preview = Some(source.clone()); |
| 1404 | spawn_insert_preview( | 1392 | previews.register_preview(settings, source, image_preview.size, worker) |
| 1405 | store, | ||
| 1406 | room_id, | ||
| 1407 | event_id, | ||
| 1408 | source, | ||
| 1409 | media, | ||
| 1410 | settings.dirs.image_previews.clone(), | ||
| 1411 | ) | ||
| 1412 | } | 1393 | } |
| 1413 | } | 1394 | } |
| 1414 | } | 1395 | } |
| @@ -1750,8 +1731,8 @@ pub struct ChatStore { | |||
| 1750 | /// Information gathered by the background thread. | 1731 | /// Information gathered by the background thread. |
| 1751 | pub sync_info: SyncInfo, | 1732 | pub sync_info: SyncInfo, |
| 1752 | 1733 | ||
| 1753 | /// Image preview "protocol" picker. | 1734 | /// Rendered image previews. |
| 1754 | pub picker: Option<Picker>, | 1735 | pub previews: PreviewManager, |
| 1755 | 1736 | ||
| 1756 | /// Last draw time, used to match with RoomInfo's draw_last. | 1737 | /// Last draw time, used to match with RoomInfo's draw_last. |
| 1757 | pub draw_curr: Option<Instant>, | 1738 | pub draw_curr: Option<Instant>, |
| @@ -1777,7 +1758,7 @@ impl ChatStore { | |||
| 1777 | ChatStore { | 1758 | ChatStore { |
| 1778 | worker, | 1759 | worker, |
| 1779 | settings, | 1760 | settings, |
| 1780 | picker, | 1761 | previews: PreviewManager::new(picker), |
| 1781 | cmds: crate::commands::setup_commands(), | 1762 | cmds: crate::commands::setup_commands(), |
| 1782 | emojis: emoji_map(), | 1763 | emojis: emoji_map(), |
| 1783 | 1764 | ||
src/config.rs +6 −20
| @@ -576,12 +576,14 @@ pub struct Notifications { | |||
| 576 | 576 | ||
| 577 | #[derive(Clone)] | 577 | #[derive(Clone)] |
| 578 | pub struct ImagePreviewValues { | 578 | pub struct ImagePreviewValues { |
| 579 | pub lazy_load: bool, | ||
| 579 | pub size: ImagePreviewSize, | 580 | pub size: ImagePreviewSize, |
| 580 | pub protocol: Option<ImagePreviewProtocolValues>, | 581 | pub protocol: Option<ImagePreviewProtocolValues>, |
| 581 | } | 582 | } |
| 582 | 583 | ||
| 583 | #[derive(Clone, Default, Deserialize)] | 584 | #[derive(Clone, Default, Deserialize)] |
| 584 | pub struct ImagePreview { | 585 | pub struct ImagePreview { |
| 586 | pub lazy_load: Option<bool>, | ||
| 585 | pub size: Option<ImagePreviewSize>, | 587 | pub size: Option<ImagePreviewSize>, |
| 586 | pub protocol: Option<ImagePreviewProtocolValues>, | 588 | pub protocol: Option<ImagePreviewProtocolValues>, |
| 587 | } | 589 | } |
| @@ -589,13 +591,14 @@ pub struct ImagePreview { | |||
| 589 | impl ImagePreview { | 591 | impl ImagePreview { |
| 590 | fn values(self) -> ImagePreviewValues { | 592 | fn values(self) -> ImagePreviewValues { |
| 591 | ImagePreviewValues { | 593 | ImagePreviewValues { |
| 594 | lazy_load: self.lazy_load.unwrap_or(true), | ||
| 592 | size: self.size.unwrap_or_default(), | 595 | size: self.size.unwrap_or_default(), |
| 593 | protocol: self.protocol, | 596 | protocol: self.protocol, |
| 594 | } | 597 | } |
| 595 | } | 598 | } |
| 596 | } | 599 | } |
| 597 | 600 | ||
| 598 | #[derive(Clone, Deserialize)] | 601 | #[derive(Clone, Copy, Deserialize, Debug)] |
| 599 | pub struct ImagePreviewSize { | 602 | pub struct ImagePreviewSize { |
| 600 | pub width: usize, | 603 | pub width: usize, |
| 601 | pub height: usize, | 604 | pub height: usize, |
| @@ -862,19 +865,17 @@ pub struct DirectoryValues { | |||
| 862 | pub data: PathBuf, | 865 | pub data: PathBuf, |
| 863 | pub logs: PathBuf, | 866 | pub logs: PathBuf, |
| 864 | pub downloads: Option<PathBuf>, | 867 | pub downloads: Option<PathBuf>, |
| 865 | pub image_previews: PathBuf, | ||
| 866 | } | 868 | } |
| 867 | 869 | ||
| 868 | impl DirectoryValues { | 870 | impl DirectoryValues { |
| 869 | fn create_dir_all(&self) -> std::io::Result<()> { | 871 | fn create_dir_all(&self) -> std::io::Result<()> { |
| 870 | use std::fs::create_dir_all; | 872 | use std::fs::create_dir_all; |
| 871 | 873 | ||
| 872 | let Self { cache, data, logs, downloads, image_previews } = self; | 874 | let Self { cache, data, logs, downloads } = self; |
| 873 | 875 | ||
| 874 | create_dir_all(cache)?; | 876 | create_dir_all(cache)?; |
| 875 | create_dir_all(data)?; | 877 | create_dir_all(data)?; |
| 876 | create_dir_all(logs)?; | 878 | create_dir_all(logs)?; |
| 877 | create_dir_all(image_previews)?; | ||
| 878 | 879 | ||
| 879 | if let Some(downloads) = downloads { | 880 | if let Some(downloads) = downloads { |
| 880 | create_dir_all(downloads)?; | 881 | create_dir_all(downloads)?; |
| @@ -890,7 +891,6 @@ pub struct Directories { | |||
| 890 | pub data: Option<String>, | 891 | pub data: Option<String>, |
| 891 | pub logs: Option<String>, | 892 | pub logs: Option<String>, |
| 892 | pub downloads: Option<String>, | 893 | pub downloads: Option<String>, |
| 893 | pub image_previews: Option<String>, | ||
| 894 | } | 894 | } |
| 895 | 895 | ||
| 896 | impl Directories { | 896 | impl Directories { |
| @@ -900,7 +900,6 @@ impl Directories { | |||
| 900 | data: self.data.or(other.data), | 900 | data: self.data.or(other.data), |
| 901 | logs: self.logs.or(other.logs), | 901 | logs: self.logs.or(other.logs), |
| 902 | downloads: self.downloads.or(other.downloads), | 902 | downloads: self.downloads.or(other.downloads), |
| 903 | image_previews: self.image_previews.or(other.image_previews), | ||
| 904 | } | 903 | } |
| 905 | } | 904 | } |
| 906 | 905 | ||
| @@ -955,20 +954,7 @@ impl Directories { | |||
| 955 | }) | 954 | }) |
| 956 | .or_else(dirs::download_dir); | 955 | .or_else(dirs::download_dir); |
| 957 | 956 | ||
| 958 | let image_previews = self | 957 | DirectoryValues { cache, data, logs, downloads } |
| 959 | .image_previews | ||
| 960 | .map(|dir| { | ||
| 961 | let dir = shellexpand::full(&dir) | ||
| 962 | .expect("unable to expand shell variables in dirs.cache"); | ||
| 963 | Path::new(dir.as_ref()).to_owned() | ||
| 964 | }) | ||
| 965 | .unwrap_or_else(|| { | ||
| 966 | let mut dir = cache.clone(); | ||
| 967 | dir.push("image_preview_downloads"); | ||
| 968 | dir | ||
| 969 | }); | ||
| 970 | |||
| 971 | DirectoryValues { cache, data, logs, downloads, image_previews } | ||
| 972 | } | 958 | } |
| 973 | } | 959 | } |
| 974 | 960 | ||
src/message/mod.rs +29 −26
| @@ -11,6 +11,7 @@ use std::ops::{Deref, DerefMut}; | |||
| 11 | use chrono::{DateTime, Local as LocalTz}; | 11 | use chrono::{DateTime, Local as LocalTz}; |
| 12 | use humansize::{format_size, DECIMAL}; | 12 | use humansize::{format_size, DECIMAL}; |
| 13 | use matrix_sdk::ruma::events::receipt::ReceiptThread; | 13 | use matrix_sdk::ruma::events::receipt::ReceiptThread; |
| 14 | use matrix_sdk::ruma::events::room::MediaSource; | ||
| 14 | use matrix_sdk::ruma::events::sticker::StickerEvent; | 15 | use matrix_sdk::ruma::events::sticker::StickerEvent; |
| 15 | use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; | 16 | use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; |
| 16 | use unicode_width::UnicodeWidthStr; | 17 | use unicode_width::UnicodeWidthStr; |
| @@ -57,6 +58,7 @@ use modalkit::prelude::*; | |||
| 57 | use ratatui_image::protocol::Protocol; | 58 | use ratatui_image::protocol::Protocol; |
| 58 | 59 | ||
| 59 | use crate::config::ImagePreviewSize; | 60 | use crate::config::ImagePreviewSize; |
| 61 | use crate::preview::{ImageStatus, PreviewManager}; | ||
| 60 | use crate::{ | 62 | use crate::{ |
| 61 | base::RoomInfo, | 63 | base::RoomInfo, |
| 62 | config::ApplicationSettings, | 64 | config::ApplicationSettings, |
| @@ -785,6 +787,7 @@ impl<'a> MessageFormatter<'a> { | |||
| 785 | text: &mut Text<'a>, | 787 | text: &mut Text<'a>, |
| 786 | info: &'a RoomInfo, | 788 | info: &'a RoomInfo, |
| 787 | settings: &'a ApplicationSettings, | 789 | settings: &'a ApplicationSettings, |
| 790 | previews: &'a PreviewManager, | ||
| 788 | ) -> Option<ProtocolPreview<'a>> { | 791 | ) -> Option<ProtocolPreview<'a>> { |
| 789 | let reply_style = if settings.tunables.message_user_color { | 792 | let reply_style = if settings.tunables.message_user_color { |
| 790 | style.patch(settings.get_user_color(&msg.sender)) | 793 | style.patch(settings.get_user_color(&msg.sender)) |
| @@ -794,7 +797,7 @@ impl<'a> MessageFormatter<'a> { | |||
| 794 | 797 | ||
| 795 | let width = self.width(); | 798 | let width = self.width(); |
| 796 | let w = width.saturating_sub(2); | 799 | let w = width.saturating_sub(2); |
| 797 | let (mut replied, proto) = msg.show_msg(w, reply_style, settings); | 800 | let (mut replied, proto) = msg.show_msg(w, reply_style, settings, previews); |
| 798 | let mut sender = msg.sender_span(info, self.settings); | 801 | let mut sender = msg.sender_span(info, self.settings); |
| 799 | let sender_width = UnicodeWidthStr::width(sender.content.as_ref()); | 802 | let sender_width = UnicodeWidthStr::width(sender.content.as_ref()); |
| 800 | let trailing = w.saturating_sub(sender_width + 1); | 803 | let trailing = w.saturating_sub(sender_width + 1); |
| @@ -895,20 +898,13 @@ impl<'a> MessageFormatter<'a> { | |||
| 895 | } | 898 | } |
| 896 | } | 899 | } |
| 897 | 900 | ||
| 898 | pub enum ImageStatus { | ||
| 899 | None, | ||
| 900 | Downloading(ImagePreviewSize), | ||
| 901 | Loaded(Protocol), | ||
| 902 | Error(String), | ||
| 903 | } | ||
| 904 | |||
| 905 | pub struct Message { | 901 | pub struct Message { |
| 906 | pub event: MessageEvent, | 902 | pub event: MessageEvent, |
| 907 | pub sender: OwnedUserId, | 903 | pub sender: OwnedUserId, |
| 908 | pub timestamp: MessageTimeStamp, | 904 | pub timestamp: MessageTimeStamp, |
| 909 | pub downloaded: bool, | 905 | pub downloaded: bool, |
| 910 | pub html: Option<StyleTree>, | 906 | pub html: Option<StyleTree>, |
| 911 | pub image_preview: ImageStatus, | 907 | pub image_preview: Option<MediaSource>, |
| 912 | } | 908 | } |
| 913 | 909 | ||
| 914 | impl Message { | 910 | impl Message { |
| @@ -922,7 +918,7 @@ impl Message { | |||
| 922 | timestamp, | 918 | timestamp, |
| 923 | downloaded, | 919 | downloaded, |
| 924 | html, | 920 | html, |
| 925 | image_preview: ImageStatus::None, | 921 | image_preview: None, |
| 926 | } | 922 | } |
| 927 | } | 923 | } |
| 928 | 924 | ||
| @@ -948,7 +944,7 @@ impl Message { | |||
| 948 | } | 944 | } |
| 949 | } | 945 | } |
| 950 | 946 | ||
| 951 | fn thread_root(&self) -> Option<OwnedEventId> { | 947 | pub fn thread_root(&self) -> Option<OwnedEventId> { |
| 952 | let content = match &self.event { | 948 | let content = match &self.event { |
| 953 | MessageEvent::EncryptedOriginal(_) => return None, | 949 | MessageEvent::EncryptedOriginal(_) => return None, |
| 954 | MessageEvent::EncryptedRedacted(_) => return None, | 950 | MessageEvent::EncryptedRedacted(_) => return None, |
| @@ -1056,6 +1052,7 @@ impl Message { | |||
| 1056 | vwctx: &ViewportContext<MessageCursor>, | 1052 | vwctx: &ViewportContext<MessageCursor>, |
| 1057 | info: &'a RoomInfo, | 1053 | info: &'a RoomInfo, |
| 1058 | settings: &'a ApplicationSettings, | 1054 | settings: &'a ApplicationSettings, |
| 1055 | previews: &'a PreviewManager, | ||
| 1059 | ) -> (Text<'a>, [Option<ProtocolPreview<'a>>; 2]) { | 1056 | ) -> (Text<'a>, [Option<ProtocolPreview<'a>>; 2]) { |
| 1060 | let width = vwctx.get_width(); | 1057 | let width = vwctx.get_width(); |
| 1061 | 1058 | ||
| @@ -1069,7 +1066,7 @@ impl Message { | |||
| 1069 | let proto_reply = reply.as_ref().and_then(|r| { | 1066 | let proto_reply = reply.as_ref().and_then(|r| { |
| 1070 | if let Some(r) = r { | 1067 | if let Some(r) = r { |
| 1071 | // Format the reply header, push it into the `Text` buffer, and get any image. | 1068 | // Format the reply header, push it into the `Text` buffer, and get any image. |
| 1072 | fmt.push_in_reply(r, style, &mut text, info, settings) | 1069 | fmt.push_in_reply(r, style, &mut text, info, settings, previews) |
| 1073 | } else { | 1070 | } else { |
| 1074 | fmt.push_spans( | 1071 | fmt.push_spans( |
| 1075 | Line::from(vec![ | 1072 | Line::from(vec![ |
| @@ -1086,7 +1083,7 @@ impl Message { | |||
| 1086 | }); | 1083 | }); |
| 1087 | 1084 | ||
| 1088 | // Now show the message contents, and the inlined reply if we couldn't find it above. | 1085 | // Now show the message contents, and the inlined reply if we couldn't find it above. |
| 1089 | let (msg, proto) = self.show_msg(width, style, settings); | 1086 | let (msg, proto) = self.show_msg(width, style, settings, previews); |
| 1090 | 1087 | ||
| 1091 | // Given our text so far, determine the image offset. | 1088 | // Given our text so far, determine the image offset. |
| 1092 | let proto_main = proto.map(|p| { | 1089 | let proto_main = proto.map(|p| { |
| @@ -1124,8 +1121,9 @@ impl Message { | |||
| 1124 | vwctx: &ViewportContext<MessageCursor>, | 1121 | vwctx: &ViewportContext<MessageCursor>, |
| 1125 | info: &'a RoomInfo, | 1122 | info: &'a RoomInfo, |
| 1126 | settings: &'a ApplicationSettings, | 1123 | settings: &'a ApplicationSettings, |
| 1124 | previews: &'a PreviewManager, | ||
| 1127 | ) -> Text<'a> { | 1125 | ) -> Text<'a> { |
| 1128 | self.show_with_preview(prev, selected, vwctx, info, settings).0 | 1126 | self.show_with_preview(prev, selected, vwctx, info, settings, previews).0 |
| 1129 | } | 1127 | } |
| 1130 | 1128 | ||
| 1131 | fn show_msg<'a>( | 1129 | fn show_msg<'a>( |
| @@ -1133,6 +1131,7 @@ impl Message { | |||
| 1133 | width: usize, | 1131 | width: usize, |
| 1134 | style: Style, | 1132 | style: Style, |
| 1135 | settings: &'a ApplicationSettings, | 1133 | settings: &'a ApplicationSettings, |
| 1134 | previews: &'a PreviewManager, | ||
| 1136 | ) -> (Text<'a>, Option<&'a Protocol>) { | 1135 | ) -> (Text<'a>, Option<&'a Protocol>) { |
| 1137 | if let Some(html) = &self.html { | 1136 | if let Some(html) = &self.html { |
| 1138 | (html.to_text(width, style, settings), None) | 1137 | (html.to_text(width, style, settings), None) |
| @@ -1147,17 +1146,21 @@ impl Message { | |||
| 1147 | } | 1146 | } |
| 1148 | 1147 | ||
| 1149 | let mut proto = None; | 1148 | let mut proto = None; |
| 1150 | let placeholder = match &self.image_preview { | 1149 | let placeholder = |
| 1151 | ImageStatus::None => None, | 1150 | match self.image_preview.as_ref().and_then(|source| previews.get(source)) { |
| 1152 | ImageStatus::Downloading(image_preview_size) => { | 1151 | None => None, |
| 1153 | placeholder_frame(Some("Downloading..."), width, image_preview_size) | 1152 | Some(ImageStatus::Queued(image_preview_size)) => { |
| 1154 | }, | 1153 | placeholder_frame(Some("Queued..."), width, image_preview_size) |
| 1155 | ImageStatus::Loaded(backend) => { | 1154 | }, |
| 1156 | proto = Some(backend); | 1155 | Some(ImageStatus::Downloading(image_preview_size)) => { |
| 1157 | placeholder_frame(Some("No Space..."), width, &backend.area().into()) | 1156 | placeholder_frame(Some("Downloading..."), width, image_preview_size) |
| 1158 | }, | 1157 | }, |
| 1159 | ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")), | 1158 | Some(ImageStatus::Loaded(backend)) => { |
| 1160 | }; | 1159 | proto = Some(backend); |
| 1160 | placeholder_frame(Some("No Space..."), width, &backend.area().into()) | ||
| 1161 | }, | ||
| 1162 | Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")), | ||
| 1163 | }; | ||
| 1161 | 1164 | ||
| 1162 | if let Some(placeholder) = placeholder { | 1165 | if let Some(placeholder) = placeholder { |
| 1163 | msg.to_mut().insert_str(0, &placeholder); | 1166 | msg.to_mut().insert_str(0, &placeholder); |
| @@ -1217,7 +1220,7 @@ impl Message { | |||
| 1217 | self.event.redact(redaction); | 1220 | self.event.redact(redaction); |
| 1218 | self.html = None; | 1221 | self.html = None; |
| 1219 | self.downloaded = false; | 1222 | self.downloaded = false; |
| 1220 | self.image_preview = ImageStatus::None; | 1223 | self.image_preview = None; |
| 1221 | } | 1224 | } |
| 1222 | } | 1225 | } |
| 1223 | 1226 | ||
src/preview.rs +130 −123
| @@ -1,11 +1,7 @@ | |||
| 1 | use std::{ | 1 | use std::{collections::HashMap, sync::Arc}; |
| 2 | fs::File, | ||
| 3 | io::{Read, Write}, | ||
| 4 | path::{Path, PathBuf}, | ||
| 5 | }; | ||
| 6 | 2 | ||
| 7 | use matrix_sdk::{ | 3 | use matrix_sdk::{ |
| 8 | media::{MediaFormat, MediaRequestParameters}, | 4 | media::{MediaFormat, MediaRequestParameters, UniqueKey}, |
| 9 | ruma::{ | 5 | ruma::{ |
| 10 | events::{ | 6 | events::{ |
| 11 | room::{ | 7 | room::{ |
| @@ -15,19 +11,102 @@ use matrix_sdk::{ | |||
| 15 | MessageLikeEvent, | 11 | MessageLikeEvent, |
| 16 | }, | 12 | }, |
| 17 | OwnedEventId, | 13 | OwnedEventId, |
| 18 | OwnedRoomId, | ||
| 19 | }, | 14 | }, |
| 20 | Media, | 15 | Media, |
| 21 | }; | 16 | }; |
| 22 | use ratatui::layout::Rect; | 17 | use ratatui::layout::Rect; |
| 23 | use ratatui_image::Resize; | 18 | use ratatui_image::{picker::Picker, protocol::Protocol, Resize}; |
| 19 | use tokio::sync::Semaphore; | ||
| 24 | 20 | ||
| 25 | use crate::{ | 21 | use crate::{ |
| 26 | base::{AsyncProgramStore, ChatStore, IambError}, | 22 | base::{AsyncProgramStore, IambError}, |
| 27 | config::ImagePreviewSize, | 23 | config::{ApplicationSettings, ImagePreviewSize}, |
| 28 | message::ImageStatus, | 24 | worker::Requester, |
| 29 | }; | 25 | }; |
| 30 | 26 | ||
| 27 | pub enum ImageStatus { | ||
| 28 | Queued(ImagePreviewSize), | ||
| 29 | Downloading(ImagePreviewSize), | ||
| 30 | Loaded(Protocol), | ||
| 31 | Error(String), | ||
| 32 | } | ||
| 33 | |||
| 34 | pub struct PreviewManager { | ||
| 35 | /// Image preview "protocol" picker. | ||
| 36 | picker: Option<Arc<Picker>>, | ||
| 37 | |||
| 38 | /// Permits for rendering images in background thread. | ||
| 39 | permits: Arc<Semaphore>, | ||
| 40 | |||
| 41 | /// Indexed by [`MediaSource::unique_key`] | ||
| 42 | previews: HashMap<String, ImageStatus>, | ||
| 43 | } | ||
| 44 | |||
| 45 | impl PreviewManager { | ||
| 46 | pub fn new(picker: Option<Picker>) -> Self { | ||
| 47 | Self { | ||
| 48 | picker: picker.map(Into::into), | ||
| 49 | permits: Arc::new(Semaphore::new(2)), | ||
| 50 | previews: Default::default(), | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | pub fn get(&self, source: &MediaSource) -> Option<&ImageStatus> { | ||
| 55 | self.previews.get(&source.unique_key()) | ||
| 56 | } | ||
| 57 | |||
| 58 | fn insert(&mut self, key: String, status: ImageStatus) { | ||
| 59 | self.previews.insert(key, status); | ||
| 60 | } | ||
| 61 | |||
| 62 | /// Queue download and preparation of preview | ||
| 63 | pub fn load(&mut self, source: &MediaSource, worker: &Requester) { | ||
| 64 | let Some(status) = self.previews.get_mut(&source.unique_key()) else { | ||
| 65 | return; | ||
| 66 | }; | ||
| 67 | let Some(picker) = &self.picker else { return }; | ||
| 68 | |||
| 69 | if let ImageStatus::Queued(size) = status { | ||
| 70 | let size = *size; | ||
| 71 | *status = ImageStatus::Downloading(size); | ||
| 72 | |||
| 73 | worker.load_image( | ||
| 74 | source.to_owned(), | ||
| 75 | size.to_owned(), | ||
| 76 | Arc::clone(picker), | ||
| 77 | Arc::clone(&self.permits), | ||
| 78 | ); | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | pub fn register_preview( | ||
| 83 | &mut self, | ||
| 84 | settings: &ApplicationSettings, | ||
| 85 | source: MediaSource, | ||
| 86 | size: ImagePreviewSize, | ||
| 87 | worker: &Requester, | ||
| 88 | ) { | ||
| 89 | if self.picker.is_none() { | ||
| 90 | return; | ||
| 91 | } | ||
| 92 | |||
| 93 | let key = source.unique_key(); | ||
| 94 | if self.previews.contains_key(&key) { | ||
| 95 | return; | ||
| 96 | } | ||
| 97 | self.previews.insert(key, ImageStatus::Queued(size)); | ||
| 98 | |||
| 99 | if settings | ||
| 100 | .tunables | ||
| 101 | .image_preview | ||
| 102 | .as_ref() | ||
| 103 | .is_some_and(|setting| !setting.lazy_load) | ||
| 104 | { | ||
| 105 | self.load(&source, worker); | ||
| 106 | } | ||
| 107 | } | ||
| 108 | } | ||
| 109 | |||
| 31 | pub fn source_from_event( | 110 | pub fn source_from_event( |
| 32 | ev: &MessageLikeEvent<RoomMessageEventContent>, | 111 | ev: &MessageLikeEvent<RoomMessageEventContent>, |
| 33 | ) -> Option<(OwnedEventId, MediaSource)> { | 112 | ) -> Option<(OwnedEventId, MediaSource)> { |
| @@ -50,126 +129,54 @@ impl From<Rect> for ImagePreviewSize { | |||
| 50 | } | 129 | } |
| 51 | } | 130 | } |
| 52 | 131 | ||
| 53 | /// Download and prepare the preview, and then lock the store to insert it. | 132 | pub async fn load_image( |
| 54 | pub fn spawn_insert_preview( | ||
| 55 | store: AsyncProgramStore, | 133 | store: AsyncProgramStore, |
| 56 | room_id: OwnedRoomId, | ||
| 57 | event_id: OwnedEventId, | ||
| 58 | source: MediaSource, | ||
| 59 | media: Media, | 134 | media: Media, |
| 60 | cache_dir: PathBuf, | 135 | source: MediaSource, |
| 136 | picker: Arc<Picker>, | ||
| 137 | permits: Arc<Semaphore>, | ||
| 138 | size: ImagePreviewSize, | ||
| 61 | ) { | 139 | ) { |
| 62 | tokio::spawn(async move { | 140 | async fn load_image_inner( |
| 63 | let img = download_or_load(event_id.to_owned(), source, media, cache_dir) | 141 | media: Media, |
| 142 | source: MediaSource, | ||
| 143 | picker: Arc<Picker>, | ||
| 144 | permits: Arc<Semaphore>, | ||
| 145 | size: ImagePreviewSize, | ||
| 146 | ) -> Result<ImageStatus, IambError> { | ||
| 147 | let reader = media | ||
| 148 | .get_media_content(&MediaRequestParameters { source, format: MediaFormat::File }, true) | ||
| 64 | .await | 149 | .await |
| 65 | .map(std::io::Cursor::new) | 150 | .map(std::io::Cursor::new) |
| 66 | .map(image::ImageReader::new) | 151 | .map(image::ImageReader::new) |
| 67 | .map_err(IambError::Matrix) | 152 | .map_err(IambError::Matrix) |
| 68 | .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError)) | 153 | .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError))?; |
| 69 | .and_then(|reader| reader.decode().map_err(IambError::Image)); | ||
| 70 | |||
| 71 | match img { | ||
| 72 | Err(err) => { | ||
| 73 | try_set_msg_preview_error( | ||
| 74 | &mut store.lock().await.application, | ||
| 75 | room_id, | ||
| 76 | event_id, | ||
| 77 | err, | ||
| 78 | ); | ||
| 79 | }, | ||
| 80 | Ok(img) => { | ||
| 81 | let mut locked = store.lock().await; | ||
| 82 | let ChatStore { rooms, picker, settings, .. } = &mut locked.application; | ||
| 83 | |||
| 84 | match picker | ||
| 85 | .as_mut() | ||
| 86 | .ok_or_else(|| IambError::Preview("Picker is empty".to_string())) | ||
| 87 | .and_then(|picker| { | ||
| 88 | Ok(( | ||
| 89 | picker, | ||
| 90 | rooms | ||
| 91 | .get_or_default(room_id.clone()) | ||
| 92 | .get_event_mut(&event_id) | ||
| 93 | .ok_or_else(|| { | ||
| 94 | IambError::Preview("Message not found".to_string()) | ||
| 95 | })?, | ||
| 96 | settings.tunables.image_preview.clone().ok_or_else(|| { | ||
| 97 | IambError::Preview("image_preview settings not found".to_string()) | ||
| 98 | })?, | ||
| 99 | )) | ||
| 100 | }) | ||
| 101 | .and_then(|(picker, msg, image_preview)| { | ||
| 102 | picker | ||
| 103 | .new_protocol(img, image_preview.size.into(), Resize::Fit(None)) | ||
| 104 | .map_err(|err| IambError::Preview(format!("{err:?}"))) | ||
| 105 | .map(|backend| (backend, msg)) | ||
| 106 | }) { | ||
| 107 | Err(err) => { | ||
| 108 | try_set_msg_preview_error(&mut locked.application, room_id, event_id, err); | ||
| 109 | }, | ||
| 110 | Ok((backend, msg)) => { | ||
| 111 | msg.image_preview = ImageStatus::Loaded(backend); | ||
| 112 | }, | ||
| 113 | } | ||
| 114 | }, | ||
| 115 | } | ||
| 116 | }); | ||
| 117 | } | ||
| 118 | 154 | ||
| 119 | fn try_set_msg_preview_error( | 155 | let image = reader.decode().map_err(IambError::Image)?; |
| 120 | application: &mut ChatStore, | ||
| 121 | room_id: OwnedRoomId, | ||
| 122 | event_id: OwnedEventId, | ||
| 123 | err: IambError, | ||
| 124 | ) { | ||
| 125 | let rooms = &mut application.rooms; | ||
| 126 | |||
| 127 | match rooms | ||
| 128 | .get_or_default(room_id.clone()) | ||
| 129 | .get_event_mut(&event_id) | ||
| 130 | .ok_or_else(|| IambError::Preview("Message not found".to_string())) | ||
| 131 | { | ||
| 132 | Ok(msg) => msg.image_preview = ImageStatus::Error(format!("{err:?}")), | ||
| 133 | Err(err) => { | ||
| 134 | tracing::error!( | ||
| 135 | "Failed to set error on msg.image_backend for event {}, room {}: {}", | ||
| 136 | event_id, | ||
| 137 | room_id, | ||
| 138 | err | ||
| 139 | ) | ||
| 140 | }, | ||
| 141 | } | ||
| 142 | } | ||
| 143 | 156 | ||
| 144 | async fn download_or_load( | 157 | let permit = permits |
| 145 | event_id: OwnedEventId, | 158 | .acquire() |
| 146 | source: MediaSource, | 159 | .await |
| 147 | media: Media, | 160 | .map_err(|err| IambError::Preview(err.to_string()))?; |
| 148 | mut cache_path: PathBuf, | 161 | |
| 149 | ) -> Result<Vec<u8>, matrix_sdk::Error> { | 162 | let handle = tokio::task::spawn_blocking(move || { |
| 150 | cache_path.push(Path::new(event_id.localpart())); | 163 | picker |
| 151 | 164 | .new_protocol(image, size.into(), Resize::Fit(None)) | |
| 152 | match File::open(&cache_path) { | 165 | .map_err(|err| IambError::Preview(err.to_string())) |
| 153 | Ok(mut f) => { | 166 | }); |
| 154 | let mut buffer = Vec::new(); | 167 | |
| 155 | f.read_to_end(&mut buffer)?; | 168 | let image = handle.await.map_err(|err| IambError::Preview(err.to_string()))??; |
| 156 | Ok(buffer) | 169 | std::mem::drop(permit); |
| 157 | }, | 170 | |
| 158 | Err(_) => { | 171 | Ok(ImageStatus::Loaded(image)) |
| 159 | media | ||
| 160 | .get_media_content( | ||
| 161 | &MediaRequestParameters { source, format: MediaFormat::File }, | ||
| 162 | true, | ||
| 163 | ) | ||
| 164 | .await | ||
| 165 | .and_then(|buffer| { | ||
| 166 | if let Err(err) = | ||
| 167 | File::create(&cache_path).and_then(|mut f| f.write_all(&buffer)) | ||
| 168 | { | ||
| 169 | return Err(err.into()); | ||
| 170 | } | ||
| 171 | Ok(buffer) | ||
| 172 | }) | ||
| 173 | }, | ||
| 174 | } | 172 | } |
| 173 | let key = source.unique_key(); | ||
| 174 | |||
| 175 | let status = match load_image_inner(media, source, picker, permits, size).await { | ||
| 176 | Ok(status) => status, | ||
| 177 | Err(err) => ImageStatus::Error(format!("{err:?}")), | ||
| 178 | }; | ||
| 179 | |||
| 180 | let mut locked = store.lock().await; | ||
| 181 | locked.application.previews.insert(key, status); | ||
| 175 | } | 182 | } |
src/tests.rs −1
| @@ -165,7 +165,6 @@ pub fn mock_dirs() -> DirectoryValues { | |||
| 165 | data: PathBuf::new(), | 165 | data: PathBuf::new(), |
| 166 | logs: PathBuf::new(), | 166 | logs: PathBuf::new(), |
| 167 | downloads: None, | 167 | downloads: None, |
| 168 | image_previews: PathBuf::new(), | ||
| 169 | } | 168 | } |
| 170 | } | 169 | } |
| 171 | 170 | ||
src/windows/room/scrollback.rs +46 −9
| @@ -55,6 +55,7 @@ use crate::{ | |||
| 55 | }, | 55 | }, |
| 56 | config::ApplicationSettings, | 56 | config::ApplicationSettings, |
| 57 | message::{Message, MessageCursor, MessageKey, Messages}, | 57 | message::{Message, MessageCursor, MessageKey, Messages}, |
| 58 | preview::PreviewManager, | ||
| 58 | }; | 59 | }; |
| 59 | 60 | ||
| 60 | fn no_msgs() -> EditError<IambInfo> { | 61 | fn no_msgs() -> EditError<IambInfo> { |
| @@ -270,6 +271,7 @@ impl ScrollbackState { | |||
| 270 | pos: MovePosition, | 271 | pos: MovePosition, |
| 271 | info: &RoomInfo, | 272 | info: &RoomInfo, |
| 272 | settings: &ApplicationSettings, | 273 | settings: &ApplicationSettings, |
| 274 | previews: &PreviewManager, | ||
| 273 | ) { | 275 | ) { |
| 274 | let Some(thread) = self.get_thread(info) else { | 276 | let Some(thread) = self.get_thread(info) else { |
| 275 | return; | 277 | return; |
| @@ -292,7 +294,8 @@ impl ScrollbackState { | |||
| 292 | for (key, item) in thread.range(..=&idx).rev() { | 294 | for (key, item) in thread.range(..=&idx).rev() { |
| 293 | let sel = selidx == key; | 295 | let sel = selidx == key; |
| 294 | let prev = prevmsg(key, thread); | 296 | let prev = prevmsg(key, thread); |
| 295 | let len = item.show(prev, sel, &self.viewctx, info, settings).lines.len(); | 297 | let len = |
| 298 | item.show(prev, sel, &self.viewctx, info, settings, previews).lines.len(); | ||
| 296 | 299 | ||
| 297 | if key == &idx { | 300 | if key == &idx { |
| 298 | lines += len / 2; | 301 | lines += len / 2; |
| @@ -315,7 +318,8 @@ impl ScrollbackState { | |||
| 315 | for (key, item) in thread.range(..=&idx).rev() { | 318 | for (key, item) in thread.range(..=&idx).rev() { |
| 316 | let sel = key == selidx; | 319 | let sel = key == selidx; |
| 317 | let prev = prevmsg(key, thread); | 320 | let prev = prevmsg(key, thread); |
| 318 | let len = item.show(prev, sel, &self.viewctx, info, settings).lines.len(); | 321 | let len = |
| 322 | item.show(prev, sel, &self.viewctx, info, settings, previews).lines.len(); | ||
| 319 | 323 | ||
| 320 | lines += len; | 324 | lines += len; |
| 321 | 325 | ||
| @@ -338,7 +342,12 @@ impl ScrollbackState { | |||
| 338 | self.jumped.push(self.cursor.clone()); | 342 | self.jumped.push(self.cursor.clone()); |
| 339 | } | 343 | } |
| 340 | 344 | ||
| 341 | fn shift_cursor(&mut self, info: &RoomInfo, settings: &ApplicationSettings) { | 345 | fn shift_cursor( |
| 346 | &mut self, | ||
| 347 | info: &RoomInfo, | ||
| 348 | settings: &ApplicationSettings, | ||
| 349 | previews: &PreviewManager, | ||
| 350 | ) { | ||
| 342 | let Some(thread) = self.get_thread(info) else { | 351 | let Some(thread) = self.get_thread(info) else { |
| 343 | return; | 352 | return; |
| 344 | }; | 353 | }; |
| @@ -368,7 +377,10 @@ impl ScrollbackState { | |||
| 368 | break; | 377 | break; |
| 369 | } | 378 | } |
| 370 | 379 | ||
| 371 | lines += item.show(prev, false, &self.viewctx, info, settings).height().max(1); | 380 | lines += item |
| 381 | .show(prev, false, &self.viewctx, info, settings, previews) | ||
| 382 | .height() | ||
| 383 | .max(1); | ||
| 372 | 384 | ||
| 373 | if lines >= self.viewctx.get_height() { | 385 | if lines >= self.viewctx.get_height() { |
| 374 | // We've reached the end of the viewport; move cursor into it. | 386 | // We've reached the end of the viewport; move cursor into it. |
| @@ -1067,6 +1079,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | |||
| 1067 | ) -> EditResult<EditInfo, IambInfo> { | 1079 | ) -> EditResult<EditInfo, IambInfo> { |
| 1068 | let info = store.application.rooms.get_or_default(self.room_id.clone()); | 1080 | let info = store.application.rooms.get_or_default(self.room_id.clone()); |
| 1069 | let settings = &store.application.settings; | 1081 | let settings = &store.application.settings; |
| 1082 | let previews = &store.application.previews; | ||
| 1070 | let mut corner = self.viewctx.corner.clone(); | 1083 | let mut corner = self.viewctx.corner.clone(); |
| 1071 | let thread = self.get_thread(info).ok_or_else(no_msgs)?; | 1084 | let thread = self.get_thread(info).ok_or_else(no_msgs)?; |
| 1072 | 1085 | ||
| @@ -1094,7 +1107,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | |||
| 1094 | for (key, item) in thread.range(..=&corner_key).rev() { | 1107 | for (key, item) in thread.range(..=&corner_key).rev() { |
| 1095 | let sel = key == cursor_key; | 1108 | let sel = key == cursor_key; |
| 1096 | let prev = prevmsg(key, thread); | 1109 | let prev = prevmsg(key, thread); |
| 1097 | let txt = item.show(prev, sel, &self.viewctx, info, settings); | 1110 | let txt = item.show(prev, sel, &self.viewctx, info, settings, previews); |
| 1098 | let len = txt.height().max(1); | 1111 | let len = txt.height().max(1); |
| 1099 | let max = len.saturating_sub(1); | 1112 | let max = len.saturating_sub(1); |
| 1100 | 1113 | ||
| @@ -1122,7 +1135,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | |||
| 1122 | 1135 | ||
| 1123 | for (key, item) in thread.range(&corner_key..) { | 1136 | for (key, item) in thread.range(&corner_key..) { |
| 1124 | let sel = key == cursor_key; | 1137 | let sel = key == cursor_key; |
| 1125 | let txt = item.show(prev, sel, &self.viewctx, info, settings); | 1138 | let txt = item.show(prev, sel, &self.viewctx, info, settings, previews); |
| 1126 | let len = txt.height().max(1); | 1139 | let len = txt.height().max(1); |
| 1127 | let max = len.saturating_sub(1); | 1140 | let max = len.saturating_sub(1); |
| 1128 | 1141 | ||
| @@ -1160,7 +1173,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | |||
| 1160 | } | 1173 | } |
| 1161 | 1174 | ||
| 1162 | self.viewctx.corner = corner; | 1175 | self.viewctx.corner = corner; |
| 1163 | self.shift_cursor(info, settings); | 1176 | self.shift_cursor(info, settings, previews); |
| 1164 | 1177 | ||
| 1165 | Ok(None) | 1178 | Ok(None) |
| 1166 | } | 1179 | } |
| @@ -1182,10 +1195,11 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | |||
| 1182 | Axis::Vertical => { | 1195 | Axis::Vertical => { |
| 1183 | let info = store.application.rooms.get_or_default(self.room_id.clone()); | 1196 | let info = store.application.rooms.get_or_default(self.room_id.clone()); |
| 1184 | let settings = &store.application.settings; | 1197 | let settings = &store.application.settings; |
| 1198 | let previews = &store.application.previews; | ||
| 1185 | let thread = self.get_thread(info).ok_or_else(no_msgs)?; | 1199 | let thread = self.get_thread(info).ok_or_else(no_msgs)?; |
| 1186 | 1200 | ||
| 1187 | if let Some(key) = self.cursor.to_key(thread).cloned() { | 1201 | if let Some(key) = self.cursor.to_key(thread).cloned() { |
| 1188 | self.scrollview(key, pos, info, settings); | 1202 | self.scrollview(key, pos, info, settings, previews); |
| 1189 | } | 1203 | } |
| 1190 | 1204 | ||
| 1191 | Ok(None) | 1205 | Ok(None) |
| @@ -1345,10 +1359,33 @@ impl StatefulWidget for Scrollback<'_> { | |||
| 1345 | let mut sawit = false; | 1359 | let mut sawit = false; |
| 1346 | let mut prev = prevmsg(&corner_key, thread); | 1360 | let mut prev = prevmsg(&corner_key, thread); |
| 1347 | 1361 | ||
| 1362 | // load image previews | ||
| 1363 | for (_, item) in thread.range(&corner_key..).rev() { | ||
| 1364 | if let Some(source) = &item.image_preview { | ||
| 1365 | self.store | ||
| 1366 | .application | ||
| 1367 | .previews | ||
| 1368 | .load(source, &self.store.application.worker); | ||
| 1369 | } | ||
| 1370 | let reply = item | ||
| 1371 | .reply_to() | ||
| 1372 | .or_else(|| item.thread_root()) | ||
| 1373 | .and_then(|e| info.get_event(&e)) | ||
| 1374 | .and_then(|msg| msg.image_preview.as_ref()); | ||
| 1375 | if let Some(source) = reply { | ||
| 1376 | self.store | ||
| 1377 | .application | ||
| 1378 | .previews | ||
| 1379 | .load(source, &self.store.application.worker); | ||
| 1380 | } | ||
| 1381 | } | ||
| 1382 | |||
| 1383 | let previews = &self.store.application.previews; | ||
| 1348 | for (key, item) in thread.range(&corner_key..) { | 1384 | for (key, item) in thread.range(&corner_key..) { |
| 1349 | let sel = key == cursor_key; | 1385 | let sel = key == cursor_key; |
| 1386 | |||
| 1350 | let (txt, [mut msg_preview, mut reply_preview]) = | 1387 | let (txt, [mut msg_preview, mut reply_preview]) = |
| 1351 | item.show_with_preview(prev, foc && sel, &state.viewctx, info, settings); | 1388 | item.show_with_preview(prev, foc && sel, &state.viewctx, info, settings, previews); |
| 1352 | 1389 | ||
| 1353 | let incomplete_ok = !full || !sel; | 1390 | let incomplete_ok = !full || !sel; |
| 1354 | 1391 | ||
src/worker.rs +50 −40
| @@ -13,7 +13,9 @@ use std::time::{Duration, Instant}; | |||
| 13 | 13 | ||
| 14 | use futures::{stream::FuturesUnordered, StreamExt}; | 14 | use futures::{stream::FuturesUnordered, StreamExt}; |
| 15 | use gethostname::gethostname; | 15 | use gethostname::gethostname; |
| 16 | use matrix_sdk::ruma::events::room::MediaSource; | ||
| 16 | use matrix_sdk::ruma::events::sticker::StickerEventContent; | 17 | use matrix_sdk::ruma::events::sticker::StickerEventContent; |
| 18 | use ratatui_image::picker::Picker; | ||
| 17 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; | 19 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; |
| 18 | use tokio::sync::Semaphore; | 20 | use tokio::sync::Semaphore; |
| 19 | use tokio::task::JoinHandle; | 21 | use tokio::task::JoinHandle; |
| @@ -89,7 +91,9 @@ use modalkit::errors::UIError; | |||
| 89 | use modalkit::prelude::{EditInfo, InfoMessage}; | 91 | use modalkit::prelude::{EditInfo, InfoMessage}; |
| 90 | 92 | ||
| 91 | use crate::base::MessageNeed; | 93 | use crate::base::MessageNeed; |
| 94 | use crate::config::ImagePreviewSize; | ||
| 92 | use crate::notifications::register_notifications; | 95 | use crate::notifications::register_notifications; |
| 96 | use crate::preview::load_image; | ||
| 93 | use crate::{ | 97 | use crate::{ |
| 94 | base::{ | 98 | base::{ |
| 95 | AsyncProgramStore, | 99 | AsyncProgramStore, |
| @@ -228,11 +232,10 @@ async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan, permit | |||
| 228 | Plan::Messages(room_id, fetch_id, message_need) => { | 232 | Plan::Messages(room_id, fetch_id, message_need) => { |
| 229 | let limit = MIN_MSG_LOAD; | 233 | let limit = MIN_MSG_LOAD; |
| 230 | let client = client.clone(); | 234 | let client = client.clone(); |
| 231 | let store_clone = store.clone(); | ||
| 232 | 235 | ||
| 233 | let res = load_older_one(&client, &room_id, fetch_id, limit).await; | 236 | let res = load_older_one(&client, &room_id, fetch_id, limit).await; |
| 234 | let mut locked = store.lock().await; | 237 | let mut locked = store.lock().await; |
| 235 | load_insert(room_id, res, locked.deref_mut(), store_clone, message_need); | 238 | load_insert(room_id, res, locked.deref_mut(), message_need); |
| 236 | }, | 239 | }, |
| 237 | Plan::Members(room_id) => { | 240 | Plan::Members(room_id) => { |
| 238 | let res = members_load(client, &room_id).await; | 241 | let res = members_load(client, &room_id).await; |
| @@ -294,13 +297,11 @@ fn load_insert( | |||
| 294 | room_id: OwnedRoomId, | 297 | room_id: OwnedRoomId, |
| 295 | res: MessageFetchResult, | 298 | res: MessageFetchResult, |
| 296 | locked: &mut ProgramStore, | 299 | locked: &mut ProgramStore, |
| 297 | store: AsyncProgramStore, | ||
| 298 | message_needs: Vec<MessageNeed>, | 300 | message_needs: Vec<MessageNeed>, |
| 299 | ) { | 301 | ) { |
| 300 | let ChatStore { presences, rooms, worker, picker, settings, .. } = &mut locked.application; | 302 | let ChatStore { presences, rooms, previews, settings, worker, .. } = &mut locked.application; |
| 301 | let info = rooms.get_or_default(room_id.clone()); | 303 | let info = rooms.get_or_default(room_id.clone()); |
| 302 | info.fetching = false; | 304 | info.fetching = false; |
| 303 | let client = &worker.client; | ||
| 304 | 305 | ||
| 305 | match res { | 306 | match res { |
| 306 | Ok((fetch_id, msgs)) => { | 307 | Ok((fetch_id, msgs)) => { |
| @@ -317,27 +318,13 @@ fn load_insert( | |||
| 317 | info.insert_encrypted(msg); | 318 | info.insert_encrypted(msg); |
| 318 | }, | 319 | }, |
| 319 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => { | 320 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => { |
| 320 | info.insert_with_preview( | 321 | info.insert_with_preview(msg, settings, previews, worker); |
| 321 | room_id.clone(), | ||
| 322 | store.clone(), | ||
| 323 | picker.clone(), | ||
| 324 | msg, | ||
| 325 | settings, | ||
| 326 | client.media(), | ||
| 327 | ); | ||
| 328 | }, | 322 | }, |
| 329 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { | 323 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { |
| 330 | info.insert_reaction(ev); | 324 | info.insert_reaction(ev); |
| 331 | }, | 325 | }, |
| 332 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { | 326 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { |
| 333 | info.insert_sticker( | 327 | info.insert_sticker(ev, settings, previews, worker); |
| 334 | room_id.clone(), | ||
| 335 | store.clone(), | ||
| 336 | picker.clone(), | ||
| 337 | ev, | ||
| 338 | settings, | ||
| 339 | client.media(), | ||
| 340 | ); | ||
| 341 | }, | 328 | }, |
| 342 | AnyTimelineEvent::MessageLike(_) => { | 329 | AnyTimelineEvent::MessageLike(_) => { |
| 343 | continue; | 330 | continue; |
| @@ -609,6 +596,7 @@ pub enum WorkerTask { | |||
| 609 | TypingNotice(OwnedRoomId), | 596 | TypingNotice(OwnedRoomId), |
| 610 | Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>), | 597 | Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>), |
| 611 | VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>), | 598 | VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>), |
| 599 | LoadImage(MediaSource, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>), | ||
| 612 | } | 600 | } |
| 613 | 601 | ||
| 614 | impl Debug for WorkerTask { | 602 | impl Debug for WorkerTask { |
| @@ -672,6 +660,14 @@ impl Debug for WorkerTask { | |||
| 672 | .field(&format_args!("_")) | 660 | .field(&format_args!("_")) |
| 673 | .finish() | 661 | .finish() |
| 674 | }, | 662 | }, |
| 663 | WorkerTask::LoadImage(source, size, _, _) => { | ||
| 664 | f.debug_tuple("WorkerTask::RenderImage") | ||
| 665 | .field(source) | ||
| 666 | .field(size) | ||
| 667 | .field(&format_args!("_")) | ||
| 668 | .field(&format_args!("_")) | ||
| 669 | .finish() | ||
| 670 | }, | ||
| 675 | } | 671 | } |
| 676 | } | 672 | } |
| 677 | } | 673 | } |
| @@ -818,6 +814,16 @@ impl Requester { | |||
| 818 | 814 | ||
| 819 | return response.recv(); | 815 | return response.recv(); |
| 820 | } | 816 | } |
| 817 | |||
| 818 | pub fn load_image( | ||
| 819 | &self, | ||
| 820 | source: MediaSource, | ||
| 821 | size: ImagePreviewSize, | ||
| 822 | picker: Arc<Picker>, | ||
| 823 | permits: Arc<Semaphore>, | ||
| 824 | ) { | ||
| 825 | self.tx.send(WorkerTask::LoadImage(source, size, picker, permits)).unwrap(); | ||
| 826 | } | ||
| 821 | } | 827 | } |
| 822 | 828 | ||
| 823 | pub struct ClientWorker { | 829 | pub struct ClientWorker { |
| @@ -826,6 +832,9 @@ pub struct ClientWorker { | |||
| 826 | client: Client, | 832 | client: Client, |
| 827 | load_handle: Option<JoinHandle<()>>, | 833 | load_handle: Option<JoinHandle<()>>, |
| 828 | sync_handle: Option<JoinHandle<()>>, | 834 | sync_handle: Option<JoinHandle<()>>, |
| 835 | |||
| 836 | /// Take care when locking since worker commands are sent with the lock already hold | ||
| 837 | store: Option<AsyncProgramStore>, | ||
| 829 | } | 838 | } |
| 830 | 839 | ||
| 831 | impl ClientWorker { | 840 | impl ClientWorker { |
| @@ -838,6 +847,7 @@ impl ClientWorker { | |||
| 838 | client: client.clone(), | 847 | client: client.clone(), |
| 839 | load_handle: None, | 848 | load_handle: None, |
| 840 | sync_handle: None, | 849 | sync_handle: None, |
| 850 | store: None, | ||
| 841 | }; | 851 | }; |
| 842 | 852 | ||
| 843 | tokio::spawn(async move { | 853 | tokio::spawn(async move { |
| @@ -911,6 +921,17 @@ impl ClientWorker { | |||
| 911 | assert!(self.initialized); | 921 | assert!(self.initialized); |
| 912 | reply.send(self.verify_request(user_id).await); | 922 | reply.send(self.verify_request(user_id).await); |
| 913 | }, | 923 | }, |
| 924 | WorkerTask::LoadImage(source, size, picker, permits) => { | ||
| 925 | assert!(self.initialized); | ||
| 926 | tokio::spawn(load_image( | ||
| 927 | self.store.clone().unwrap(), | ||
| 928 | self.client.media(), | ||
| 929 | source, | ||
| 930 | picker, | ||
| 931 | permits, | ||
| 932 | size, | ||
| 933 | )); | ||
| 934 | }, | ||
| 914 | } | 935 | } |
| 915 | } | 936 | } |
| 916 | 937 | ||
| @@ -985,20 +1006,14 @@ impl ClientWorker { | |||
| 985 | let sender = ev.sender().to_owned(); | 1006 | let sender = ev.sender().to_owned(); |
| 986 | let _ = locked.application.presences.get_or_default(sender); | 1007 | let _ = locked.application.presences.get_or_default(sender); |
| 987 | 1008 | ||
| 988 | let ChatStore { rooms, picker, settings, .. } = &mut locked.application; | 1009 | let ChatStore { rooms, previews, settings, worker, .. } = |
| 1010 | &mut locked.application; | ||
| 989 | let info = rooms.get_or_default(room_id.to_owned()); | 1011 | let info = rooms.get_or_default(room_id.to_owned()); |
| 990 | 1012 | ||
| 991 | update_event_receipts(info, &room, ev.event_id()).await; | 1013 | update_event_receipts(info, &room, ev.event_id()).await; |
| 992 | 1014 | ||
| 993 | let full_ev = ev.into_full_event(room_id.to_owned()); | 1015 | let full_ev = ev.into_full_event(room_id.to_owned()); |
| 994 | info.insert_with_preview( | 1016 | info.insert_with_preview(full_ev, settings, previews, worker); |
| 995 | room_id.to_owned(), | ||
| 996 | store.clone(), | ||
| 997 | picker.clone(), | ||
| 998 | full_ev, | ||
| 999 | settings, | ||
| 1000 | client.media(), | ||
| 1001 | ); | ||
| 1002 | } | 1017 | } |
| 1003 | }, | 1018 | }, |
| 1004 | ); | 1019 | ); |
| @@ -1025,7 +1040,6 @@ impl ClientWorker { | |||
| 1025 | let _ = self.client.add_event_handler( | 1040 | let _ = self.client.add_event_handler( |
| 1026 | |ev: SyncMessageLikeEvent<StickerEventContent>, | 1041 | |ev: SyncMessageLikeEvent<StickerEventContent>, |
| 1027 | room: MatrixRoom, | 1042 | room: MatrixRoom, |
| 1028 | client: Client, | ||
| 1029 | store: Ctx<AsyncProgramStore>| { | 1043 | store: Ctx<AsyncProgramStore>| { |
| 1030 | async move { | 1044 | async move { |
| 1031 | let room_id = room.room_id(); | 1045 | let room_id = room.room_id(); |
| @@ -1035,21 +1049,15 @@ impl ClientWorker { | |||
| 1035 | let sender = ev.sender().to_owned(); | 1049 | let sender = ev.sender().to_owned(); |
| 1036 | let _ = locked.application.presences.get_or_default(sender); | 1050 | let _ = locked.application.presences.get_or_default(sender); |
| 1037 | 1051 | ||
| 1038 | let ChatStore { rooms, picker, settings, .. } = &mut locked.application; | 1052 | let ChatStore { rooms, settings, previews, worker, .. } = |
| 1053 | &mut locked.application; | ||
| 1039 | 1054 | ||
| 1040 | let info = rooms.get_or_default(room_id.to_owned()); | 1055 | let info = rooms.get_or_default(room_id.to_owned()); |
| 1041 | 1056 | ||
| 1042 | update_event_receipts(info, &room, ev.event_id()).await; | 1057 | update_event_receipts(info, &room, ev.event_id()).await; |
| 1043 | 1058 | ||
| 1044 | let full_ev = ev.into_full_event(room_id.to_owned()); | 1059 | let full_ev = ev.into_full_event(room_id.to_owned()); |
| 1045 | info.insert_sticker( | 1060 | info.insert_sticker(full_ev, settings, previews, worker); |
| 1046 | room_id.to_owned(), | ||
| 1047 | store.clone(), | ||
| 1048 | picker.clone(), | ||
| 1049 | full_ev, | ||
| 1050 | settings, | ||
| 1051 | client.media(), | ||
| 1052 | ); | ||
| 1053 | } | 1061 | } |
| 1054 | }, | 1062 | }, |
| 1055 | ); | 1063 | ); |
| @@ -1234,6 +1242,8 @@ impl ClientWorker { | |||
| 1234 | }, | 1242 | }, |
| 1235 | ); | 1243 | ); |
| 1236 | 1244 | ||
| 1245 | self.store = Some(store.clone()); | ||
| 1246 | |||
| 1237 | self.load_handle = tokio::spawn({ | 1247 | self.load_handle = tokio::spawn({ |
| 1238 | let client = self.client.clone(); | 1248 | let client = self.client.clone(); |
| 1239 | let settings = self.settings.clone(); | 1249 | let settings = self.settings.clone(); |