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:
44 github_token: ${{ secrets.GITHUB_TOKEN }} 44 github_token: ${{ secrets.GITHUB_TOKEN }}
45 reporter: 'github-check' 45 reporter: 'github-check'
46 - name: Run tests 46 - name: Run tests
47 run: cargo test 47 run: cargo test ${{ matrix.platform == 'windows-latest' && '--no-default-features' || '' }}
48 - name: Build artifacts 48 - name: Build artifacts
49 run: cargo build --release 49 run: cargo build --release ${{ matrix.platform == 'windows-latest' && '--no-default-features' || '' }}
50 - name: Upload artifacts 50 - name: Upload artifacts
51 uses: actions/upload-artifact@master 51 uses: actions/upload-artifact@master
52 with: 52 with:
Cargo.lock +67 −2
@@ -685,6 +685,22 @@ dependencies = [
685 "cfg-if", 685 "cfg-if",
686] 686]
687 687
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
688[[package]] 704[[package]]
689name = "crossterm" 705name = "crossterm"
690version = "0.27.0" 706version = "0.27.0"
@@ -940,6 +956,12 @@ dependencies = [
940 "syn 2.0.38", 956 "syn 2.0.38",
941] 957]
942 958
959[[package]]
960name = "dyn-clone"
961version = "1.0.14"
962source = "registry+https://github.com/rust-lang/crates.io-index"
963checksum = "23d2f3407d9a573d666de4b5bdf10569d73ca9478087346697dcbae6244bfbcd"
964
943[[package]] 965[[package]]
944name = "ed25519" 966name = "ed25519"
945version = "1.5.3" 967version = "1.5.3"
@@ -1595,6 +1617,7 @@ dependencies = [
1595 "modalkit", 1617 "modalkit",
1596 "open", 1618 "open",
1597 "pretty_assertions", 1619 "pretty_assertions",
1620 "ratatui-image",
1598 "regex", 1621 "regex",
1599 "rpassword", 1622 "rpassword",
1600 "serde", 1623 "serde",
@@ -1910,6 +1933,12 @@ version = "0.1.1"
1910source = "registry+https://github.com/rust-lang/crates.io-index" 1933source = "registry+https://github.com/rust-lang/crates.io-index"
1911checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" 1934checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
1912 1935
1936[[package]]
1937name = "make-cmd"
1938version = "0.1.0"
1939source = "registry+https://github.com/rust-lang/crates.io-index"
1940checksum = "a8ca8afbe8af1785e09636acb5a41e08a765f5f0340568716c18a8700ba3c0d3"
1941
1913[[package]] 1942[[package]]
1914name = "malloc_buf" 1943name = "malloc_buf"
1915version = "0.0.6" 1944version = "0.0.6"
@@ -2219,7 +2248,7 @@ dependencies = [
2219 "anymap2", 2248 "anymap2",
2220 "arboard", 2249 "arboard",
2221 "bitflags 1.3.2", 2250 "bitflags 1.3.2",
2222 "crossterm", 2251 "crossterm 0.27.0",
2223 "derive_more", 2252 "derive_more",
2224 "intervaltree", 2253 "intervaltree",
2225 "libc", 2254 "libc",
@@ -2842,7 +2871,7 @@ checksum = "2e2e4cd95294a85c3b4446e63ef054eea43e0205b1fd60120c16b74ff7ff96ad"
2842dependencies = [ 2871dependencies = [
2843 "bitflags 2.4.0", 2872 "bitflags 2.4.0",
2844 "cassowary", 2873 "cassowary",
2845 "crossterm", 2874 "crossterm 0.27.0",
2846 "indoc", 2875 "indoc",
2847 "itertools 0.11.0", 2876 "itertools 0.11.0",
2848 "paste", 2877 "paste",
@@ -2851,6 +2880,23 @@ dependencies = [
2851 "unicode-width", 2880 "unicode-width",
2852] 2881]
2853 2882
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
2854[[package]] 2900[[package]]
2855name = "rayon" 2901name = "rayon"
2856version = "1.8.0" 2902version = "1.8.0"
@@ -3392,6 +3438,25 @@ version = "0.3.11"
3392source = "registry+https://github.com/rust-lang/crates.io-index" 3438source = "registry+https://github.com/rust-lang/crates.io-index"
3393checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" 3439checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
3394 3440
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
3395[[package]] 3460[[package]]
3396name = "slab" 3461name = "slab"
3397version = "0.4.9" 3462version = "0.4.9"
Cargo.toml +5
@@ -40,6 +40,7 @@ markup5ever_rcdom = "0.2.0"
40mime = "^0.3.16" 40mime = "^0.3.16"
41mime_guess = "^2.0.4" 41mime_guess = "^2.0.4"
42open = "3.2.0" 42open = "3.2.0"
43ratatui-image = { version = "0.4.1", features = ["serde"] }
43regex = "^1.5" 44regex = "^1.5"
44rpassword = "^7.2" 45rpassword = "^7.2"
45serde = "^1.0" 46serde = "^1.0"
@@ -74,3 +75,7 @@ pretty_assertions = "1.4.0"
74[profile.release] 75[profile.release]
75lto = true 76lto = true
76incremental = false 77incremental = false
78
79[features]
80default = ["sixel"]
81sixel = ["ratatui-image/sixel"]
README.md +1
@@ -104,6 +104,7 @@ two other TUI clients and Element Web:
104| Room upgrades | ❌ ([#41]) | ✔️ | ❌ | ✔️ | 104| Room upgrades | ❌ ([#41]) | ✔️ | ❌ | ✔️ |
105| Localisations | ❌ | 1 | ❌ | 44 | 105| Localisations | ❌ | 1 | ❌ | 44 |
106| SSO Support | ✔️ | ✔️ | ✔️ | ✔️ | 106| SSO Support | ✔️ | ✔️ | ✔️ | ✔️ |
107| Image preview | ✔️ | ❌ | ❌ | ✔️ |
107 108
108## License 109## License
109 110
docs/example_config.json +10 −1
@@ -23,7 +23,16 @@
23 "color": "magenta" 23 "color": "magenta"
24 } 24 }
25 }, 25 },
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 }
27 }, 36 },
28 "dirs": { 37 "dirs": {
29 "cache": "/home/user/.cache/iamb/", 38 "cache": "/home/user/.cache/iamb/",
docs/iamb.5.md +15
@@ -82,6 +82,18 @@ overridden as described in *PROFILES*.
82**default_room** (type: string) 82**default_room** (type: string)
83> The room to show by default instead of a welcome-screen. 83> The room to show by default instead of a welcome-screen.
84 84
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
85## USER OVERRIDES 97## USER OVERRIDES
86 98
87Overrides are mapped onto matrix User IDs such as _@user:matrix.org_ and are 99Overrides 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
127**downloads** (type: string) 139**downloads** (type: string)
128> Specifies where to store downloaded files. 140> Specifies where to store downloaded files.
129 141
142**image_previews** (type: string)
143> Specifies where to store automatically downloaded image previews.
144
130# SEE ALSO 145# SEE ALSO
131 146
132*iamb(1)* 147*iamb(1)*
flake.nix +11 −4
@@ -22,18 +22,25 @@
22 pname = "iamb"; 22 pname = "iamb";
23 version = "0.0.7"; 23 version = "0.0.7";
24 src = ./.; 24 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 };
26 nativeBuildInputs = [ pkgs.pkgconfig ]; 32 nativeBuildInputs = [ pkgs.pkgconfig ];
27 buildInputs = [ pkgs.openssl ] ++ pkgs.lib.optionals pkgs.stdenv.isDarwin 33 buildInputs = [ pkgs.openssl ] ++ pkgs.lib.optionals pkgs.stdenv.isDarwin
28 (with pkgs.darwin.apple_sdk.frameworks; [ AppKit Security ]); 34 (with pkgs.darwin.apple_sdk.frameworks; [ AppKit Security ]);
29 }; 35 };
30 devShell = mkShell { 36 devShell = mkShell {
31 buildInputs = [ 37 buildInputs = [
32 (rustNightly.override { extensions = [ "rust-src" ]; }) 38 (rustNightly.override {
39 extensions = [ "rust-src" "rust-analyzer-preview" "rustfmt" "clippy" ];
40 })
33 pkg-config 41 pkg-config
34 cargo-tarpaulin 42 cargo-tarpaulin
35 rust-analyzer 43 cargo-watch
36 rustfmt
37 ]; 44 ];
38 }; 45 };
39 }); 46 });
src/base.rs +99 −1
@@ -11,6 +11,7 @@ use std::sync::Arc;
11use std::time::{Duration, Instant}; 11use std::time::{Duration, Instant};
12 12
13use emojis::Emoji; 13use emojis::Emoji;
14use ratatui_image::picker::{Picker, ProtocolType};
14use serde::{ 15use serde::{
15 de::Error as SerdeError, 16 de::Error as SerdeError,
16 de::Visitor, 17 de::Visitor,
@@ -81,6 +82,9 @@ use modalkit::{
81 }, 82 },
82}; 83};
83 84
85use crate::config::ImagePreviewProtocolValues;
86use crate::message::ImageStatus;
87use crate::preview::{source_from_event, spawn_insert_preview};
84use crate::{ 88use crate::{
85 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}, 89 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
86 worker::Requester, 90 worker::Requester,
@@ -617,6 +621,14 @@ pub enum IambError {
617 /// A failure to access the system's clipboard. 621 /// A failure to access the system's clipboard.
618 #[error("Could not use system clipboard data")] 622 #[error("Could not use system clipboard data")]
619 Clipboard, 623 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),
620} 632}
621 633
622impl From<IambError> for UIError<IambInfo> { 634impl From<IambError> for UIError<IambInfo> {
@@ -737,6 +749,11 @@ impl RoomInfo {
737 self.messages.get(self.get_message_key(event_id)?) 749 self.messages.get(self.get_message_key(event_id)?)
738 } 750 }
739 751
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
740 /// Insert a reaction to a message. 757 /// Insert a reaction to a message.
741 pub fn insert_reaction(&mut self, react: ReactionEvent) { 758 pub fn insert_reaction(&mut self, react: ReactionEvent) {
742 match react { 759 match react {
@@ -827,6 +844,37 @@ impl RoomInfo {
827 } 844 }
828 } 845 }
829 846
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
830 /// Indicates whether we've recently fetched scrollback for this room. 878 /// Indicates whether we've recently fetched scrollback for this room.
831 pub fn recently_fetched(&self) -> bool { 879 pub fn recently_fetched(&self) -> bool {
832 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE) 880 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
@@ -936,6 +984,51 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
936 return emojis; 984 return emojis;
937} 985}
938 986
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
939/// Information gathered during server syncs about joined rooms. 1032/// Information gathered during server syncs about joined rooms.
940#[derive(Default)] 1033#[derive(Default)]
941pub struct SyncInfo { 1034pub struct SyncInfo {
@@ -980,15 +1073,20 @@ pub struct ChatStore {
980 1073
981 /// Information gathered by the background thread. 1074 /// Information gathered by the background thread.
982 pub sync_info: SyncInfo, 1075 pub sync_info: SyncInfo,
1076
1077 /// Image preview "protocol" picker.
1078 pub picker: Option<Picker>,
983} 1079}
984 1080
985impl ChatStore { 1081impl ChatStore {
986 /// Create a new [ChatStore]. 1082 /// Create a new [ChatStore].
987 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self { 1083 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1084 let picker = picker_from_settings(&settings);
1085
988 ChatStore { 1086 ChatStore {
989 worker, 1087 worker,
990 settings, 1088 settings,
991 1089 picker,
992 cmds: crate::commands::setup_commands(), 1090 cmds: crate::commands::setup_commands(),
993 emojis: emoji_map(), 1091 emojis: emoji_map(),
994 1092
src/config.rs +54 −1
@@ -11,6 +11,7 @@ use std::process;
11 11
12use clap::Parser; 12use clap::Parser;
13use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 13use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
14use ratatui_image::picker::ProtocolType;
14use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer}; 15use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
15use tracing::Level; 16use tracing::Level;
16use url::Url; 17use url::Url;
@@ -266,6 +267,45 @@ pub enum UserDisplayStyle {
266 DisplayName, 267 DisplayName,
267} 268}
268 269
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
269#[derive(Clone)] 309#[derive(Clone)]
270pub struct SortValues { 310pub struct SortValues {
271 pub dms: Vec<SortColumn<SortFieldRoom>>, 311 pub dms: Vec<SortColumn<SortFieldRoom>>,
@@ -308,6 +348,7 @@ pub struct TunableValues {
308 pub username_display: UserDisplayStyle, 348 pub username_display: UserDisplayStyle,
309 pub default_room: Option<String>, 349 pub default_room: Option<String>,
310 pub open_command: Option<Vec<String>>, 350 pub open_command: Option<Vec<String>>,
351 pub image_preview: Option<ImagePreviewValues>,
311} 352}
312 353
313#[derive(Clone, Default, Deserialize)] 354#[derive(Clone, Default, Deserialize)]
@@ -326,6 +367,7 @@ pub struct Tunables {
326 pub username_display: Option<UserDisplayStyle>, 367 pub username_display: Option<UserDisplayStyle>,
327 pub default_room: Option<String>, 368 pub default_room: Option<String>,
328 pub open_command: Option<Vec<String>>, 369 pub open_command: Option<Vec<String>>,
370 pub image_preview: Option<ImagePreview>,
329} 371}
330 372
331impl Tunables { 373impl Tunables {
@@ -346,6 +388,7 @@ impl Tunables {
346 username_display: self.username_display.or(other.username_display), 388 username_display: self.username_display.or(other.username_display),
347 default_room: self.default_room.or(other.default_room), 389 default_room: self.default_room.or(other.default_room),
348 open_command: self.open_command.or(other.open_command), 390 open_command: self.open_command.or(other.open_command),
391 image_preview: self.image_preview.or(other.image_preview),
349 } 392 }
350 } 393 }
351 394
@@ -364,6 +407,7 @@ impl Tunables {
364 username_display: self.username_display.unwrap_or_default(), 407 username_display: self.username_display.unwrap_or_default(),
365 default_room: self.default_room, 408 default_room: self.default_room,
366 open_command: self.open_command, 409 open_command: self.open_command,
410 image_preview: self.image_preview.map(ImagePreview::values),
367 } 411 }
368 } 412 }
369} 413}
@@ -373,6 +417,7 @@ pub struct DirectoryValues {
373 pub cache: PathBuf, 417 pub cache: PathBuf,
374 pub logs: PathBuf, 418 pub logs: PathBuf,
375 pub downloads: Option<PathBuf>, 419 pub downloads: Option<PathBuf>,
420 pub image_previews: PathBuf,
376} 421}
377 422
378#[derive(Clone, Default, Deserialize)] 423#[derive(Clone, Default, Deserialize)]
@@ -380,6 +425,7 @@ pub struct Directories {
380 pub cache: Option<PathBuf>, 425 pub cache: Option<PathBuf>,
381 pub logs: Option<PathBuf>, 426 pub logs: Option<PathBuf>,
382 pub downloads: Option<PathBuf>, 427 pub downloads: Option<PathBuf>,
428 pub image_previews: Option<PathBuf>,
383} 429}
384 430
385impl Directories { 431impl Directories {
@@ -388,6 +434,7 @@ impl Directories {
388 cache: self.cache.or(other.cache), 434 cache: self.cache.or(other.cache),
389 logs: self.logs.or(other.logs), 435 logs: self.logs.or(other.logs),
390 downloads: self.downloads.or(other.downloads), 436 downloads: self.downloads.or(other.downloads),
437 image_previews: self.image_previews.or(other.image_previews),
391 } 438 }
392 } 439 }
393 440
@@ -409,7 +456,13 @@ impl Directories {
409 456
410 let downloads = self.downloads.or_else(dirs::download_dir); 457 let downloads = self.downloads.or_else(dirs::download_dir);
411 458
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 }
413 } 466 }
414} 467}
415 468
src/main.rs +3
@@ -68,6 +68,7 @@ mod commands;
68mod config; 68mod config;
69mod keybindings; 69mod keybindings;
70mod message; 70mod message;
71mod preview;
71mod util; 72mod util;
72mod windows; 73mod windows;
73mod worker; 74mod worker;
@@ -267,6 +268,7 @@ impl Application {
267 let screen = setup_screen(settings, locked.deref_mut())?; 268 let screen = setup_screen(settings, locked.deref_mut())?;
268 269
269 let worker = locked.application.worker.clone(); 270 let worker = locked.application.worker.clone();
271
270 drop(locked); 272 drop(locked);
271 273
272 let actstack = VecDeque::new(); 274 let actstack = VecDeque::new();
@@ -786,6 +788,7 @@ fn main() -> IambResult<()> {
786 let log_dir = settings.dirs.logs.as_path(); 788 let log_dir = settings.dirs.logs.as_path();
787 789
788 create_dir_all(settings.matrix_dir.as_path())?; 790 create_dir_all(settings.matrix_dir.as_path())?;
791 create_dir_all(settings.dirs.image_previews.as_path())?;
789 create_dir_all(log_dir)?; 792 create_dir_all(log_dir)?;
790 793
791 let appender = tracing_appender::rolling::daily(log_dir, log_prefix); 794 let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
src/message/mod.rs +79 −1
@@ -51,7 +51,9 @@ use modalkit::tui::{
51}; 51};
52 52
53use modalkit::editing::{base::ViewportContext, cursor::Cursor}; 53use modalkit::editing::{base::ViewportContext, cursor::Cursor};
54use ratatui_image::protocol::Protocol;
54 55
56use crate::config::ImagePreviewSize;
55use crate::{ 57use crate::{
56 base::{IambResult, RoomInfo}, 58 base::{IambResult, RoomInfo},
57 config::ApplicationSettings, 59 config::ApplicationSettings,
@@ -585,12 +587,20 @@ impl<'a> MessageFormatter<'a> {
585 } 587 }
586} 588}
587 589
590pub enum ImageStatus {
591 None,
592 Downloading(ImagePreviewSize),
593 Loaded(Box<dyn Protocol>),
594 Error(String),
595}
596
588pub struct Message { 597pub struct Message {
589 pub event: MessageEvent, 598 pub event: MessageEvent,
590 pub sender: OwnedUserId, 599 pub sender: OwnedUserId,
591 pub timestamp: MessageTimeStamp, 600 pub timestamp: MessageTimeStamp,
592 pub downloaded: bool, 601 pub downloaded: bool,
593 pub html: Option<StyleTree>, 602 pub html: Option<StyleTree>,
603 pub image_preview: ImageStatus,
594} 604}
595 605
596impl Message { 606impl Message {
@@ -598,7 +608,14 @@ impl Message {
598 let html = event.html(); 608 let html = event.html();
599 let downloaded = false; 609 let downloaded = false;
600 610
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 }
602 } 619 }
603 620
604 pub fn reply_to(&self) -> Option<OwnedEventId> { 621 pub fn reply_to(&self) -> Option<OwnedEventId> {
@@ -681,6 +698,36 @@ impl Message {
681 } 698 }
682 } 699 }
683 700
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
684 pub fn show<'a>( 731 pub fn show<'a>(
685 &'a self, 732 &'a self,
686 prev: Option<&Message>, 733 prev: Option<&Message>,
@@ -791,6 +838,19 @@ impl Message {
791 msg.to_mut().push_str(" \u{2705}"); 838 msg.to_mut().push_str(" \u{2705}");
792 } 839 }
793 840
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
794 wrapped_text(msg, width, style) 854 wrapped_text(msg, width, style)
795 } 855 }
796 } 856 }
@@ -803,6 +863,24 @@ impl Message {
803 settings.get_user_span(self.sender.as_ref(), info) 863 settings.get_user_span(self.sender.as_ref(), info)
804 } 864 }
805 865
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
806 fn show_sender<'a>( 884 fn show_sender<'a>(
807 &'a self, 885 &'a self,
808 prev: Option<&Message>, 886 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 {
172 cache: PathBuf::new(), 172 cache: PathBuf::new(),
173 logs: PathBuf::new(), 173 logs: PathBuf::new(),
174 downloads: None, 174 downloads: None,
175 image_previews: PathBuf::new(),
175 } 176 }
176} 177}
177 178
@@ -195,6 +196,7 @@ pub fn mock_tunables() -> TunableValues {
195 .collect::<HashMap<_, _>>(), 196 .collect::<HashMap<_, _>>(),
196 open_command: None, 197 open_command: None,
197 username_display: UserDisplayStyle::Username, 198 username_display: UserDisplayStyle::Username,
199 image_preview: None,
198 } 200 }
199} 201}
200 202
src/windows/room/scrollback.rs +34 −4
@@ -1,6 +1,7 @@
1//! Message scrollback 1//! Message scrollback
2use std::collections::HashSet; 2use std::collections::HashSet;
3 3
4use ratatui_image::FixedImage;
4use regex::Regex; 5use regex::Regex;
5 6
6use matrix_sdk::ruma::OwnedRoomId; 7use matrix_sdk::ruma::OwnedRoomId;
@@ -1264,6 +1265,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1264 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { 1265 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1265 let info = self.store.application.rooms.get_or_default(state.room_id.clone()); 1266 let info = self.store.application.rooms.get_or_default(state.room_id.clone());
1266 let settings = &self.store.application.settings; 1267 let settings = &self.store.application.settings;
1268 let picker = &self.store.application.picker;
1267 let area = if state.cursor.timestamp.is_some() { 1269 let area = if state.cursor.timestamp.is_some() {
1268 render_jump_to_recent(area, buf, self.focused) 1270 render_jump_to_recent(area, buf, self.focused)
1269 } else { 1271 } else {
@@ -1307,7 +1309,11 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1307 let sel = key == cursor_key; 1309 let sel = key == cursor_key;
1308 let txt = item.show(prev, foc && sel, &state.viewctx, info, settings); 1310 let txt = item.show(prev, foc && sel, &state.viewctx, info, settings);
1309 1311
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 };
1311 1317
1312 let incomplete_ok = !full || !sel; 1318 let incomplete_ok = !full || !sel;
1313 1319
@@ -1323,9 +1329,17 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1323 continue; 1329 continue;
1324 } 1330 }
1325 1331
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));
1327 sawit |= sel; 1339 sawit |= sel;
1328 } 1340 }
1341
1342 prev = Some(item);
1329 } 1343 }
1330 1344
1331 if lines.len() > height { 1345 if lines.len() > height {
@@ -1333,7 +1347,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1333 let _ = lines.drain(..n); 1347 let _ = lines.drain(..n);
1334 } 1348 }
1335 1349
1336 if let Some(((ts, event_id), row, _)) = lines.first() { 1350 if let Some(((ts, event_id), row, _, _)) = lines.first() {
1337 state.viewctx.corner.timestamp = Some((*ts, event_id.clone())); 1351 state.viewctx.corner.timestamp = Some((*ts, event_id.clone()));
1338 state.viewctx.corner.text_row = *row; 1352 state.viewctx.corner.text_row = *row;
1339 } 1353 }
@@ -1341,11 +1355,27 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1341 let mut y = area.top(); 1355 let mut y = area.top();
1342 let x = area.left(); 1356 let x = area.left();
1343 1357
1344 for (_, _, txt) in lines.into_iter() { 1358 let mut image_previews = vec![];
1359 for ((_, _), _, txt, line_preview) in lines.into_iter() {
1345 let _ = buf.set_line(x, y, &txt, area.width); 1360 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 }
1346 1364
1347 y += 1; 1365 y += 1;
1348 } 1366 }
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 }
1349 1379
1350 if self.room_focused && 1380 if self.room_focused &&
1351 settings.tunables.read_receipt_send && 1381 settings.tunables.read_receipt_send &&
src/worker.rs +34 −13
@@ -244,16 +244,20 @@ async fn load_older_one(
244 } 244 }
245} 245}
246 246
247async fn load_insert( 247async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) {
248 client: &Client,
249 room_id: OwnedRoomId,
250 res: MessageFetchResult,
251 store: AsyncProgramStore,
252) {
253 let mut locked = store.lock().await; 248 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;
255 let info = rooms.get_or_default(room_id.clone()); 258 let info = rooms.get_or_default(room_id.clone());
256 info.fetching = false; 259 info.fetching = false;
260 let client = &worker.client;
257 261
258 match res { 262 match res {
259 Ok((fetch_id, msgs)) => { 263 Ok((fetch_id, msgs)) => {
@@ -270,7 +274,14 @@ async fn load_insert(
270 info.insert_encrypted(msg); 274 info.insert_encrypted(msg);
271 }, 275 },
272 AnyMessageLikeEvent::RoomMessage(msg) => { 276 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 );
274 }, 285 },
275 AnyMessageLikeEvent::Reaction(ev) => { 286 AnyMessageLikeEvent::Reaction(ev) => {
276 info.insert_reaction(ev); 287 info.insert_reaction(ev);
@@ -298,12 +309,11 @@ async fn load_older(client: &Client, store: &AsyncProgramStore) -> usize {
298 .await 309 .await
299 .into_iter() 310 .into_iter()
300 .map(|(room_id, fetch_id)| { 311 .map(|(room_id, fetch_id)| {
301 let client = client.clone();
302 let store = store.clone(); 312 let store = store.clone();
303 313
304 async move { 314 async move {
305 let res = load_older_one(&client, room_id.as_ref(), fetch_id, limit).await; 315 let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
306 load_insert(&client, room_id, res, store).await; 316 load_insert(room_id, res, store).await;
307 } 317 }
308 }) 318 })
309 .collect::<FuturesUnordered<_>>() 319 .collect::<FuturesUnordered<_>>()
@@ -813,9 +823,20 @@ impl ClientWorker {
813 let sender = ev.sender().to_owned(); 823 let sender = ev.sender().to_owned();
814 let _ = locked.application.presences.get_or_default(sender); 824 let _ = locked.application.presences.get_or_default(sender);
815 825
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
817 update_event_receipts(info, &room, ev.event_id()).await; 829 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 );
819 } 840 }
820 }, 841 },
821 ); 842 );