Commit 221faa828d

221faa828df1842abb1680b572cfb39b85289331

parent: 974775b29b

Unregistered key

Benjamin Grosse <ste3ls@gmail.com> · 2023-11-16 16:36 UTC
committer: <noreply@github.com>

Add support for previewing images in room scrollback (#108)

Layout: unified · split

.github/workflows/ci.yml +2 −2
@@ -44,9 +44,9 @@ jobs:
4444 github_token: ${{ secrets.GITHUB_TOKEN }}
4545 reporter: 'github-check'
4646 - name: Run tests
47 run: cargo test
47 run: cargo test ${{ matrix.platform == 'windows-latest' && '--no-default-features' || '' }}
4848 - name: Build artifacts
49 run: cargo build --release
49 run: cargo build --release ${{ matrix.platform == 'windows-latest' && '--no-default-features' || '' }}
5050 - name: Upload artifacts
5151 uses: actions/upload-artifact@master
5252 with:
Cargo.lock +67 −2
@@ -685,6 +685,22 @@ dependencies = [
685685 "cfg-if",
686686]
687687
688[[package]]
689name = "crossterm"
690version = "0.25.0"
691source = "registry+https://github.com/rust-lang/crates.io-index"
692checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
693dependencies = [
694 "bitflags 1.3.2",
695 "crossterm_winapi",
696 "libc",
697 "mio",
698 "parking_lot 0.12.1",
699 "signal-hook",
700 "signal-hook-mio",
701 "winapi",
702]
703
688704[[package]]
689705name = "crossterm"
690706version = "0.27.0"
@@ -940,6 +956,12 @@ dependencies = [
940956 "syn 2.0.38",
941957]
942958
959[[package]]
960name = "dyn-clone"
961version = "1.0.14"
962source = "registry+https://github.com/rust-lang/crates.io-index"
963checksum = "23d2f3407d9a573d666de4b5bdf10569d73ca9478087346697dcbae6244bfbcd"
964
943965[[package]]
944966name = "ed25519"
945967version = "1.5.3"
@@ -1595,6 +1617,7 @@ dependencies = [
15951617 "modalkit",
15961618 "open",
15971619 "pretty_assertions",
1620 "ratatui-image",
15981621 "regex",
15991622 "rpassword",
16001623 "serde",
@@ -1910,6 +1933,12 @@ version = "0.1.1"
19101933source = "registry+https://github.com/rust-lang/crates.io-index"
19111934checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
19121935
1936[[package]]
1937name = "make-cmd"
1938version = "0.1.0"
1939source = "registry+https://github.com/rust-lang/crates.io-index"
1940checksum = "a8ca8afbe8af1785e09636acb5a41e08a765f5f0340568716c18a8700ba3c0d3"
1941
19131942[[package]]
19141943name = "malloc_buf"
19151944version = "0.0.6"
@@ -2219,7 +2248,7 @@ dependencies = [
22192248 "anymap2",
22202249 "arboard",
22212250 "bitflags 1.3.2",
2222 "crossterm",
2251 "crossterm 0.27.0",
22232252 "derive_more",
22242253 "intervaltree",
22252254 "libc",
@@ -2842,7 +2871,7 @@ checksum = "2e2e4cd95294a85c3b4446e63ef054eea43e0205b1fd60120c16b74ff7ff96ad"
28422871dependencies = [
28432872 "bitflags 2.4.0",
28442873 "cassowary",
2845 "crossterm",
2874 "crossterm 0.27.0",
28462875 "indoc",
28472876 "itertools 0.11.0",
28482877 "paste",
@@ -2851,6 +2880,23 @@ dependencies = [
28512880 "unicode-width",
28522881]
28532882
2883[[package]]
2884name = "ratatui-image"
2885version = "0.4.1"
2886source = "registry+https://github.com/rust-lang/crates.io-index"
2887checksum = "a3a43ba44f10847b9f76f54e528832b0d63029ce48be7663fb8ddded27ac1457"
2888dependencies = [
2889 "base64 0.21.4",
2890 "crossterm 0.25.0",
2891 "dyn-clone",
2892 "image",
2893 "rand 0.8.5",
2894 "ratatui",
2895 "rustix 0.38.17",
2896 "serde",
2897 "sixel-bytes",
2898]
2899
28542900[[package]]
28552901name = "rayon"
28562902version = "1.8.0"
@@ -3392,6 +3438,25 @@ version = "0.3.11"
33923438source = "registry+https://github.com/rust-lang/crates.io-index"
33933439checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
33943440
3441[[package]]
3442name = "sixel-bytes"
3443version = "0.2.3"
3444source = "registry+https://github.com/rust-lang/crates.io-index"
3445checksum = "45cad296a72571e80953823496e9a55caf893e264de9a7c5cfd29427fca720fc"
3446dependencies = [
3447 "sixel-sys-static",
3448]
3449
3450[[package]]
3451name = "sixel-sys-static"
3452version = "0.3.2"
3453source = "registry+https://github.com/rust-lang/crates.io-index"
3454checksum = "2988846c5099382a880a7dd385d38b203a60430710a9c22e538d500e6908f4f9"
3455dependencies = [
3456 "make-cmd",
3457 "pkg-config",
3458]
3459
33953460[[package]]
33963461name = "slab"
33973462version = "0.4.9"
Cargo.toml +5
@@ -40,6 +40,7 @@ markup5ever_rcdom = "0.2.0"
4040mime = "^0.3.16"
4141mime_guess = "^2.0.4"
4242open = "3.2.0"
43ratatui-image = { version = "0.4.1", features = ["serde"] }
4344regex = "^1.5"
4445rpassword = "^7.2"
4546serde = "^1.0"
@@ -74,3 +75,7 @@ pretty_assertions = "1.4.0"
7475[profile.release]
7576lto = true
7677incremental = false
78
79[features]
80default = ["sixel"]
81sixel = ["ratatui-image/sixel"]
README.md +1
@@ -104,6 +104,7 @@ two other TUI clients and Element Web:
104104| Room upgrades | ❌ ([#41]) | ✔️ | ❌ | ✔️ |
105105| Localisations | ❌ | 1 | ❌ | 44 |
106106| SSO Support | ✔️ | ✔️ | ✔️ | ✔️ |
107| Image preview | ✔️ | ❌ | ❌ | ✔️ |
107108
108109## License
109110
docs/example_config.json +10 −1
@@ -23,7 +23,16 @@
2323 "color": "magenta"
2424 }
2525 },
26 "default_room": "#iamb-users:0x.badd.cafe"
26 "default_room": "#iamb-users:0x.badd.cafe",
27 "image_preview": {
28 "protocol": {
29 "type": "sixel"
30 },
31 "size": {
32 "width": 66,
33 "height": 10
34 }
35 }
2736 },
2837 "dirs": {
2938 "cache": "/home/user/.cache/iamb/",
docs/iamb.5.md +15
@@ -82,6 +82,18 @@ overridden as described in *PROFILES*.
8282**default_room** (type: string)
8383> The room to show by default instead of a welcome-screen.
8484
85**image_preview** (type: image_preview object)
86> Enable image previews and configure it. An empty object will enable the
87> feature with default settings, omitting it will disable the feature.
88> *size* is an optional object with *width* and *height* numbers, which are
89> used to set the preview size in characters. Defaults to 66 and 10.
90> *protocol* is an optional object to override settings that should normally
91> be guessed automatically.
92> *protocol.type* is an optional string with one of the protocol types:
93> _sixel_, _kitty_, _halfblocks_.
94> *protocol.font_size* is an optional list of two numbers representing font
95> width and height in pixels.
96
8597## USER OVERRIDES
8698
8799Overrides are mapped onto matrix User IDs such as _@user:matrix.org_ and are
@@ -127,6 +139,9 @@ Specifies the directories to save data in. Configured as a map under the key
127139**downloads** (type: string)
128140> Specifies where to store downloaded files.
129141
142**image_previews** (type: string)
143> Specifies where to store automatically downloaded image previews.
144
130145# SEE ALSO
131146
132147*iamb(1)*
flake.nix +11 −4
@@ -22,18 +22,25 @@
2222 pname = "iamb";
2323 version = "0.0.7";
2424 src = ./.;
25 cargoLock.lockFile = ./Cargo.lock;
25 cargoLock = {
26 lockFile = ./Cargo.lock;
27 # Remove this once modalkit gets pinned by version again.
28 outputHashes = {
29 "modalkit-0.0.16" = "sha256-mjAD1v0r2+SzPdoB2wZ/5iJ1NZK+3OSvCYcUZ5Ef38Y=";
30 };
31 };
2632 nativeBuildInputs = [ pkgs.pkgconfig ];
2733 buildInputs = [ pkgs.openssl ] ++ pkgs.lib.optionals pkgs.stdenv.isDarwin
2834 (with pkgs.darwin.apple_sdk.frameworks; [ AppKit Security ]);
2935 };
3036 devShell = mkShell {
3137 buildInputs = [
32 (rustNightly.override { extensions = [ "rust-src" ]; })
38 (rustNightly.override {
39 extensions = [ "rust-src" "rust-analyzer-preview" "rustfmt" "clippy" ];
40 })
3341 pkg-config
3442 cargo-tarpaulin
35 rust-analyzer
36 rustfmt
43 cargo-watch
3744 ];
3845 };
3946 });
src/base.rs +99 −1
@@ -11,6 +11,7 @@ use std::sync::Arc;
1111use std::time::{Duration, Instant};
1212
1313use emojis::Emoji;
14use ratatui_image::picker::{Picker, ProtocolType};
1415use serde::{
1516 de::Error as SerdeError,
1617 de::Visitor,
@@ -81,6 +82,9 @@ use modalkit::{
8182 },
8283};
8384
85use crate::config::ImagePreviewProtocolValues;
86use crate::message::ImageStatus;
87use crate::preview::{source_from_event, spawn_insert_preview};
8488use crate::{
8589 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
8690 worker::Requester,
@@ -617,6 +621,14 @@ pub enum IambError {
617621 /// A failure to access the system's clipboard.
618622 #[error("Could not use system clipboard data")]
619623 Clipboard,
624
625 /// An failure during disk/network/ipc/etc. I/O.
626 #[error("Input/Output error: {0}")]
627 IOError(#[from] std::io::Error),
628
629 /// A failure while trying to show an image preview.
630 #[error("Preview error: {0}")]
631 Preview(String),
620632}
621633
622634impl From<IambError> for UIError<IambInfo> {
@@ -737,6 +749,11 @@ impl RoomInfo {
737749 self.messages.get(self.get_message_key(event_id)?)
738750 }
739751
752 /// Get an event for an identifier as mutable.
753 pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
754 self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
755 }
756
740757 /// Insert a reaction to a message.
741758 pub fn insert_reaction(&mut self, react: ReactionEvent) {
742759 match react {
@@ -827,6 +844,37 @@ impl RoomInfo {
827844 }
828845 }
829846
847 /// Insert a new message event, and spawn a task for image-preview if it has an image
848 /// attachment.
849 pub fn insert_with_preview(
850 &mut self,
851 room_id: OwnedRoomId,
852 store: AsyncProgramStore,
853 picker: Option<Picker>,
854 ev: RoomMessageEvent,
855 settings: &mut ApplicationSettings,
856 media: matrix_sdk::Media,
857 ) {
858 let source = picker.and_then(|_| source_from_event(&ev));
859 self.insert(ev);
860
861 if let Some((event_id, source)) = source {
862 if let (Some(msg), Some(image_preview)) =
863 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
864 {
865 msg.image_preview = ImageStatus::Downloading(image_preview.size.clone());
866 spawn_insert_preview(
867 store,
868 room_id,
869 event_id,
870 source,
871 media,
872 settings.dirs.image_previews.clone(),
873 )
874 }
875 }
876 }
877
830878 /// Indicates whether we've recently fetched scrollback for this room.
831879 pub fn recently_fetched(&self) -> bool {
832880 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
@@ -936,6 +984,51 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
936984 return emojis;
937985}
938986
987#[cfg(unix)]
988fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
989 let mut picker = match Picker::from_termios() {
990 Ok(picker) => picker,
991 Err(e) => {
992 tracing::error!("Failed to setup image previews: {e}");
993 return None;
994 },
995 };
996
997 if let Some(protocol_type) = protocol_type {
998 picker.protocol_type = protocol_type;
999 } else {
1000 picker.guess_protocol();
1001 }
1002
1003 Some(picker)
1004}
1005
1006/// Windows cannot guess the right protocol, and always needs type and font_size.
1007#[cfg(windows)]
1008fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1009 tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1010 None
1011}
1012
1013fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1014 let image_preview = settings.tunables.image_preview.as_ref()?;
1015 let image_preview_protocol = image_preview.protocol.as_ref();
1016
1017 if let Some(&ImagePreviewProtocolValues {
1018 r#type: Some(protocol_type),
1019 font_size: Some(font_size),
1020 }) = image_preview_protocol
1021 {
1022 // User forced type and font_size: use that.
1023 let mut picker = Picker::new(font_size);
1024 picker.protocol_type = protocol_type;
1025 Some(picker)
1026 } else {
1027 // Guess, but use type if forced.
1028 picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1029 }
1030}
1031
9391032/// Information gathered during server syncs about joined rooms.
9401033#[derive(Default)]
9411034pub struct SyncInfo {
@@ -980,15 +1073,20 @@ pub struct ChatStore {
9801073
9811074 /// Information gathered by the background thread.
9821075 pub sync_info: SyncInfo,
1076
1077 /// Image preview "protocol" picker.
1078 pub picker: Option<Picker>,
9831079}
9841080
9851081impl ChatStore {
9861082 /// Create a new [ChatStore].
9871083 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1084 let picker = picker_from_settings(&settings);
1085
9881086 ChatStore {
9891087 worker,
9901088 settings,
991
1089 picker,
9921090 cmds: crate::commands::setup_commands(),
9931091 emojis: emoji_map(),
9941092
src/config.rs +54 −1
@@ -11,6 +11,7 @@ use std::process;
1111
1212use clap::Parser;
1313use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
14use ratatui_image::picker::ProtocolType;
1415use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
1516use tracing::Level;
1617use url::Url;
@@ -266,6 +267,45 @@ pub enum UserDisplayStyle {
266267 DisplayName,
267268}
268269
270#[derive(Clone)]
271pub struct ImagePreviewValues {
272 pub size: ImagePreviewSize,
273 pub protocol: Option<ImagePreviewProtocolValues>,
274}
275
276#[derive(Clone, Default, Deserialize)]
277pub struct ImagePreview {
278 pub size: Option<ImagePreviewSize>,
279 pub protocol: Option<ImagePreviewProtocolValues>,
280}
281
282impl ImagePreview {
283 fn values(self) -> ImagePreviewValues {
284 ImagePreviewValues {
285 size: self.size.unwrap_or_default(),
286 protocol: self.protocol,
287 }
288 }
289}
290
291#[derive(Clone, Deserialize)]
292pub struct ImagePreviewSize {
293 pub width: usize,
294 pub height: usize,
295}
296
297impl Default for ImagePreviewSize {
298 fn default() -> Self {
299 ImagePreviewSize { width: 66, height: 10 }
300 }
301}
302
303#[derive(Clone, Deserialize)]
304pub struct ImagePreviewProtocolValues {
305 pub r#type: Option<ProtocolType>,
306 pub font_size: Option<(u16, u16)>,
307}
308
269309#[derive(Clone)]
270310pub struct SortValues {
271311 pub dms: Vec<SortColumn<SortFieldRoom>>,
@@ -308,6 +348,7 @@ pub struct TunableValues {
308348 pub username_display: UserDisplayStyle,
309349 pub default_room: Option<String>,
310350 pub open_command: Option<Vec<String>>,
351 pub image_preview: Option<ImagePreviewValues>,
311352}
312353
313354#[derive(Clone, Default, Deserialize)]
@@ -326,6 +367,7 @@ pub struct Tunables {
326367 pub username_display: Option<UserDisplayStyle>,
327368 pub default_room: Option<String>,
328369 pub open_command: Option<Vec<String>>,
370 pub image_preview: Option<ImagePreview>,
329371}
330372
331373impl Tunables {
@@ -346,6 +388,7 @@ impl Tunables {
346388 username_display: self.username_display.or(other.username_display),
347389 default_room: self.default_room.or(other.default_room),
348390 open_command: self.open_command.or(other.open_command),
391 image_preview: self.image_preview.or(other.image_preview),
349392 }
350393 }
351394
@@ -364,6 +407,7 @@ impl Tunables {
364407 username_display: self.username_display.unwrap_or_default(),
365408 default_room: self.default_room,
366409 open_command: self.open_command,
410 image_preview: self.image_preview.map(ImagePreview::values),
367411 }
368412 }
369413}
@@ -373,6 +417,7 @@ pub struct DirectoryValues {
373417 pub cache: PathBuf,
374418 pub logs: PathBuf,
375419 pub downloads: Option<PathBuf>,
420 pub image_previews: PathBuf,
376421}
377422
378423#[derive(Clone, Default, Deserialize)]
@@ -380,6 +425,7 @@ pub struct Directories {
380425 pub cache: Option<PathBuf>,
381426 pub logs: Option<PathBuf>,
382427 pub downloads: Option<PathBuf>,
428 pub image_previews: Option<PathBuf>,
383429}
384430
385431impl Directories {
@@ -388,6 +434,7 @@ impl Directories {
388434 cache: self.cache.or(other.cache),
389435 logs: self.logs.or(other.logs),
390436 downloads: self.downloads.or(other.downloads),
437 image_previews: self.image_previews.or(other.image_previews),
391438 }
392439 }
393440
@@ -409,7 +456,13 @@ impl Directories {
409456
410457 let downloads = self.downloads.or_else(dirs::download_dir);
411458
412 DirectoryValues { cache, logs, downloads }
459 let image_previews = self.image_previews.unwrap_or_else(|| {
460 let mut dir = cache.clone();
461 dir.push("image_preview_downloads");
462 dir
463 });
464
465 DirectoryValues { cache, logs, downloads, image_previews }
413466 }
414467}
415468
src/main.rs +3
@@ -68,6 +68,7 @@ mod commands;
6868mod config;
6969mod keybindings;
7070mod message;
71mod preview;
7172mod util;
7273mod windows;
7374mod worker;
@@ -267,6 +268,7 @@ impl Application {
267268 let screen = setup_screen(settings, locked.deref_mut())?;
268269
269270 let worker = locked.application.worker.clone();
271
270272 drop(locked);
271273
272274 let actstack = VecDeque::new();
@@ -786,6 +788,7 @@ fn main() -> IambResult<()> {
786788 let log_dir = settings.dirs.logs.as_path();
787789
788790 create_dir_all(settings.matrix_dir.as_path())?;
791 create_dir_all(settings.dirs.image_previews.as_path())?;
789792 create_dir_all(log_dir)?;
790793
791794 let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
src/message/mod.rs +79 −1
@@ -51,7 +51,9 @@ use modalkit::tui::{
5151};
5252
5353use modalkit::editing::{base::ViewportContext, cursor::Cursor};
54use ratatui_image::protocol::Protocol;
5455
56use crate::config::ImagePreviewSize;
5557use crate::{
5658 base::{IambResult, RoomInfo},
5759 config::ApplicationSettings,
@@ -585,12 +587,20 @@ impl<'a> MessageFormatter<'a> {
585587 }
586588}
587589
590pub enum ImageStatus {
591 None,
592 Downloading(ImagePreviewSize),
593 Loaded(Box<dyn Protocol>),
594 Error(String),
595}
596
588597pub struct Message {
589598 pub event: MessageEvent,
590599 pub sender: OwnedUserId,
591600 pub timestamp: MessageTimeStamp,
592601 pub downloaded: bool,
593602 pub html: Option<StyleTree>,
603 pub image_preview: ImageStatus,
594604}
595605
596606impl Message {
@@ -598,7 +608,14 @@ impl Message {
598608 let html = event.html();
599609 let downloaded = false;
600610
601 Message { event, sender, timestamp, downloaded, html }
611 Message {
612 event,
613 sender,
614 timestamp,
615 downloaded,
616 html,
617 image_preview: ImageStatus::None,
618 }
602619 }
603620
604621 pub fn reply_to(&self) -> Option<OwnedEventId> {
@@ -681,6 +698,36 @@ impl Message {
681698 }
682699 }
683700
701 /// Get the image preview Protocol and x,y offset, based on get_render_format.
702 pub fn line_preview<'a>(
703 &'a self,
704 prev: Option<&Message>,
705 vwctx: &ViewportContext<MessageCursor>,
706 info: &'a RoomInfo,
707 ) -> Option<(&dyn Protocol, u16, u16)> {
708 let width = vwctx.get_width();
709 // The x position where get_render_format would render the text.
710 let x = (if USER_GUTTER + MIN_MSG_LEN <= width {
711 USER_GUTTER
712 } else {
713 0
714 } + 1) as u16;
715 // See get_render_format; account for possible "date" line.
716 let date_y = match &prev {
717 Some(prev) if !prev.timestamp.same_day(&self.timestamp) => 1,
718 _ => 0,
719 };
720 if let ImageStatus::Loaded(backend) = &self.image_preview {
721 return Some((backend.as_ref(), x, date_y));
722 } else if let Some(reply) = self.reply_to().and_then(|e| info.get_event(&e)) {
723 if let ImageStatus::Loaded(backend) = &reply.image_preview {
724 // The reply should be offset a bit:
725 return Some((backend.as_ref(), x + 2, date_y + 1));
726 }
727 }
728 None
729 }
730
684731 pub fn show<'a>(
685732 &'a self,
686733 prev: Option<&Message>,
@@ -791,6 +838,19 @@ impl Message {
791838 msg.to_mut().push_str(" \u{2705}");
792839 }
793840
841 if let Some(placeholder) = match &self.image_preview {
842 ImageStatus::None => None,
843 ImageStatus::Downloading(image_preview_size) => {
844 Some(Message::placeholder_frame(Some("Downloading..."), image_preview_size))
845 },
846 ImageStatus::Loaded(backend) => {
847 Some(Message::placeholder_frame(None, &backend.rect().into()))
848 },
849 ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")),
850 } {
851 msg.to_mut().insert_str(0, &placeholder);
852 }
853
794854 wrapped_text(msg, width, style)
795855 }
796856 }
@@ -803,6 +863,24 @@ impl Message {
803863 settings.get_user_span(self.sender.as_ref(), info)
804864 }
805865
866 /// Before the image is loaded, already display a placeholder frame of the image size.
867 fn placeholder_frame(text: Option<&str>, image_preview_size: &ImagePreviewSize) -> String {
868 let ImagePreviewSize { width, height } = image_preview_size;
869 let mut placeholder = "\u{230c}".to_string();
870 placeholder.push_str(&" ".repeat(width - 2));
871 placeholder.push_str("\u{230d}\n");
872 placeholder.push(' ');
873 if let Some(text) = text {
874 placeholder.push_str(text);
875 }
876
877 placeholder.push_str(&"\n".repeat(height - 2));
878 placeholder.push('\u{230e}');
879 placeholder.push_str(&" ".repeat(width - 2));
880 placeholder.push_str("\u{230f}\n");
881 placeholder
882 }
883
806884 fn show_sender<'a>(
807885 &'a self,
808886 prev: Option<&Message>,
src/preview.rs added +172
@@ -0,0 +1,172 @@
1use std::{
2 fs::File,
3 io::{Read, Write},
4 path::{Path, PathBuf},
5};
6
7use matrix_sdk::{
8 media::{MediaFormat, MediaRequest},
9 ruma::{
10 events::{
11 room::{
12 message::{MessageType, RoomMessageEventContent},
13 MediaSource,
14 },
15 MessageLikeEvent,
16 },
17 OwnedEventId,
18 OwnedRoomId,
19 },
20 Media,
21};
22use modalkit::tui::layout::Rect;
23use ratatui_image::Resize;
24
25use crate::{
26 base::{AsyncProgramStore, ChatStore, IambError},
27 config::ImagePreviewSize,
28 message::ImageStatus,
29};
30
31pub fn source_from_event(
32 ev: &MessageLikeEvent<RoomMessageEventContent>,
33) -> Option<(OwnedEventId, MediaSource)> {
34 if let MessageLikeEvent::Original(ev) = &ev {
35 if let MessageType::Image(c) = &ev.content.msgtype {
36 return Some((ev.event_id.clone(), c.source.clone()));
37 }
38 }
39 None
40}
41
42impl From<ImagePreviewSize> for Rect {
43 fn from(value: ImagePreviewSize) -> Self {
44 Rect::new(0, 0, value.width as _, value.height as _)
45 }
46}
47impl From<Rect> for ImagePreviewSize {
48 fn from(rect: Rect) -> Self {
49 ImagePreviewSize { width: rect.width as _, height: rect.height as _ }
50 }
51}
52
53/// Download and prepare the preview, and then lock the store to insert it.
54pub fn spawn_insert_preview(
55 store: AsyncProgramStore,
56 room_id: OwnedRoomId,
57 event_id: OwnedEventId,
58 source: MediaSource,
59 media: Media,
60 cache_dir: PathBuf,
61) {
62 tokio::spawn(async move {
63 let img = download_or_load(event_id.to_owned(), source, media, cache_dir)
64 .await
65 .map(std::io::Cursor::new)
66 .map(image::io::Reader::new)
67 .map_err(IambError::Matrix)
68 .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)
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
119fn try_set_msg_preview_error(
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
144async fn download_or_load(
145 event_id: OwnedEventId,
146 source: MediaSource,
147 media: Media,
148 mut cache_path: PathBuf,
149) -> Result<Vec<u8>, matrix_sdk::Error> {
150 cache_path.push(Path::new(event_id.localpart()));
151
152 match File::open(&cache_path) {
153 Ok(mut f) => {
154 let mut buffer = Vec::new();
155 f.read_to_end(&mut buffer)?;
156 Ok(buffer)
157 },
158 Err(_) => {
159 media
160 .get_media_content(&MediaRequest { source, format: MediaFormat::File }, true)
161 .await
162 .and_then(|buffer| {
163 if let Err(err) =
164 File::create(&cache_path).and_then(|mut f| f.write_all(&buffer))
165 {
166 return Err(err.into());
167 }
168 Ok(buffer)
169 })
170 },
171 }
172}
src/tests.rs +2
@@ -172,6 +172,7 @@ pub fn mock_dirs() -> DirectoryValues {
172172 cache: PathBuf::new(),
173173 logs: PathBuf::new(),
174174 downloads: None,
175 image_previews: PathBuf::new(),
175176 }
176177}
177178
@@ -195,6 +196,7 @@ pub fn mock_tunables() -> TunableValues {
195196 .collect::<HashMap<_, _>>(),
196197 open_command: None,
197198 username_display: UserDisplayStyle::Username,
199 image_preview: None,
198200 }
199201}
200202
src/windows/room/scrollback.rs +34 −4
@@ -1,6 +1,7 @@
11//! Message scrollback
22use std::collections::HashSet;
33
4use ratatui_image::FixedImage;
45use regex::Regex;
56
67use matrix_sdk::ruma::OwnedRoomId;
@@ -1264,6 +1265,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
12641265 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
12651266 let info = self.store.application.rooms.get_or_default(state.room_id.clone());
12661267 let settings = &self.store.application.settings;
1268 let picker = &self.store.application.picker;
12671269 let area = if state.cursor.timestamp.is_some() {
12681270 render_jump_to_recent(area, buf, self.focused)
12691271 } else {
@@ -1307,7 +1309,11 @@ impl<'a> StatefulWidget for Scrollback<'a> {
13071309 let sel = key == cursor_key;
13081310 let txt = item.show(prev, foc && sel, &state.viewctx, info, settings);
13091311
1310 prev = Some(item);
1312 let mut msg_preview = if picker.is_some() {
1313 item.line_preview(prev, &state.viewctx, info)
1314 } else {
1315 None
1316 };
13111317
13121318 let incomplete_ok = !full || !sel;
13131319
@@ -1323,9 +1329,17 @@ impl<'a> StatefulWidget for Scrollback<'a> {
13231329 continue;
13241330 }
13251331
1326 lines.push((key, row, line));
1332 let line_preview = match msg_preview {
1333 // Only take the preview into the matching row number.
1334 Some((_, _, y)) if y as usize == row => msg_preview.take(),
1335 _ => None,
1336 };
1337
1338 lines.push((key, row, line, line_preview));
13271339 sawit |= sel;
13281340 }
1341
1342 prev = Some(item);
13291343 }
13301344
13311345 if lines.len() > height {
@@ -1333,7 +1347,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
13331347 let _ = lines.drain(..n);
13341348 }
13351349
1336 if let Some(((ts, event_id), row, _)) = lines.first() {
1350 if let Some(((ts, event_id), row, _, _)) = lines.first() {
13371351 state.viewctx.corner.timestamp = Some((*ts, event_id.clone()));
13381352 state.viewctx.corner.text_row = *row;
13391353 }
@@ -1341,11 +1355,27 @@ impl<'a> StatefulWidget for Scrollback<'a> {
13411355 let mut y = area.top();
13421356 let x = area.left();
13431357
1344 for (_, _, txt) in lines.into_iter() {
1358 let mut image_previews = vec![];
1359 for ((_, _), _, txt, line_preview) in lines.into_iter() {
13451360 let _ = buf.set_line(x, y, &txt, area.width);
1361 if let Some((backend, msg_x, _)) = line_preview {
1362 image_previews.push((x + msg_x, y, backend));
1363 }
13461364
13471365 y += 1;
13481366 }
1367 // Render image previews after all text lines have been drawn, as the render might draw below the current
1368 // line.
1369 for (x, y, backend) in image_previews {
1370 let image_widget = FixedImage::new(backend);
1371 let mut rect = backend.rect();
1372 rect.x = x;
1373 rect.y = y;
1374 // Don't render outside of scrollback area
1375 if rect.bottom() <= area.bottom() && rect.right() <= area.right() {
1376 image_widget.render(rect, buf);
1377 }
1378 }
13491379
13501380 if self.room_focused &&
13511381 settings.tunables.read_receipt_send &&
src/worker.rs +34 −13
@@ -244,16 +244,20 @@ async fn load_older_one(
244244 }
245245}
246246
247async fn load_insert(
248 client: &Client,
249 room_id: OwnedRoomId,
250 res: MessageFetchResult,
251 store: AsyncProgramStore,
252) {
247async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) {
253248 let mut locked = store.lock().await;
254 let ChatStore { need_load, presences, rooms, .. } = &mut locked.application;
249 let ChatStore {
250 need_load,
251 presences,
252 rooms,
253 worker,
254 picker,
255 settings,
256 ..
257 } = &mut locked.application;
255258 let info = rooms.get_or_default(room_id.clone());
256259 info.fetching = false;
260 let client = &worker.client;
257261
258262 match res {
259263 Ok((fetch_id, msgs)) => {
@@ -270,7 +274,14 @@ async fn load_insert(
270274 info.insert_encrypted(msg);
271275 },
272276 AnyMessageLikeEvent::RoomMessage(msg) => {
273 info.insert(msg);
277 info.insert_with_preview(
278 room_id.clone(),
279 store.clone(),
280 *picker,
281 msg,
282 settings,
283 client.media(),
284 );
274285 },
275286 AnyMessageLikeEvent::Reaction(ev) => {
276287 info.insert_reaction(ev);
@@ -298,12 +309,11 @@ async fn load_older(client: &Client, store: &AsyncProgramStore) -> usize {
298309 .await
299310 .into_iter()
300311 .map(|(room_id, fetch_id)| {
301 let client = client.clone();
302312 let store = store.clone();
303313
304314 async move {
305 let res = load_older_one(&client, room_id.as_ref(), fetch_id, limit).await;
306 load_insert(&client, room_id, res, store).await;
315 let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
316 load_insert(room_id, res, store).await;
307317 }
308318 })
309319 .collect::<FuturesUnordered<_>>()
@@ -813,9 +823,20 @@ impl ClientWorker {
813823 let sender = ev.sender().to_owned();
814824 let _ = locked.application.presences.get_or_default(sender);
815825
816 let info = locked.application.get_room_info(room_id.to_owned());
826 let ChatStore { rooms, picker, settings, .. } = &mut locked.application;
827 let info = rooms.get_or_default(room_id.to_owned());
828
817829 update_event_receipts(info, &room, ev.event_id()).await;
818 info.insert(ev.into_full_event(room_id.to_owned()));
830
831 let full_ev = ev.into_full_event(room_id.to_owned());
832 info.insert_with_preview(
833 room_id.to_owned(),
834 store.clone(),
835 *picker,
836 full_ev,
837 settings,
838 client.media(),
839 );
819840 }
820841 },
821842 );