Commit 83b503e4a9

83b503e4a9323b52b2af8607d8f7e773f2c0fd8b

parent: cda6bf1180

Unregistered key

vaw <git@nlih.de> · 2026-08-16 05:47 UTC
committer: <noreply@github.com>

Support media captions (#592)

Layout: unified · split

src/base.rs +7 −2
@@ -491,10 +491,15 @@ pub enum SendAction {
491491 SubmitFromEditor,
492492
493493 /// Upload a file.
494 Upload(String),
494 ///
495 /// The second argument indicates whether to use the messagebar as a caption, don't use it or
496 /// ask the user.
497 Upload(String, Option<bool>),
495498
496499 /// Upload the image data.
497 UploadImage(usize, usize, Cow<'static, [u8]>),
500 ///
501 /// The [`bool`] arguments indicates whether to use the messagebar as a caption.
502 UploadImage(usize, usize, Cow<'static, [u8]>, bool),
498503}
499504
500505/// An action performed against the user's homeserver.
src/commands.rs +1 −1
@@ -675,7 +675,7 @@ fn iamb_upload(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
675675 return Result::Err(CommandError::InvalidArgument);
676676 }
677677
678 let sact = SendAction::Upload(args.remove(0));
678 let sact = SendAction::Upload(args.remove(0), None);
679679 let iact = IambAction::from(sact);
680680 let step = CommandStep::Continue(iact.into(), ctx.context.clone());
681681
src/message/compose.rs +28
@@ -180,6 +180,34 @@ pub fn text_to_message(input: String) -> RoomMessageEventContent {
180180 RoomMessageEventContent::new(msg)
181181}
182182
183/// Returns `None` if `input` contains a non-text slash command.
184pub fn text_to_text_message_event_content(input: String) -> Option<TextMessageEventContent> {
185 let cmd = parse_slash_command(&input);
186
187 let content = match cmd {
188 Ok((body, SlashCommand::Html)) => TextMessageEventContent::html(body, body),
189 Ok((body, SlashCommand::Plaintext)) => TextMessageEventContent::plain(body),
190 Ok((body, SlashCommand::Markdown)) => {
191 if let Some(html) = text_to_html(body) {
192 TextMessageEventContent::html(body, html)
193 } else {
194 TextMessageEventContent::plain(body)
195 }
196 },
197 Ok(_) => return None,
198
199 _ => {
200 if let Some(html) = text_to_html(&input) {
201 TextMessageEventContent::html(input, html)
202 } else {
203 TextMessageEventContent::plain(input)
204 }
205 },
206 };
207
208 Some(content)
209}
210
183211#[cfg(test)]
184212pub mod tests {
185213 use super::*;
src/message/mod.rs +111 −56
@@ -73,7 +73,7 @@ mod html;
7373mod printer;
7474mod state;
7575
76pub use self::compose::text_to_message;
76pub use self::compose::{text_to_message, text_to_text_message_event_content};
7777use self::state::{body_cow_state, html_state};
7878pub use html::TreeGenState;
7979
@@ -462,17 +462,33 @@ impl MessageEvent {
462462 MessageEvent::Local(_, _, content) => content,
463463 };
464464
465 if let MessageType::Text(content) = &content.msgtype {
466 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
467 Some(parse_matrix_html(body.as_str()))
468 } else {
469 None
470 }
465 let formatted = match &content.msgtype {
466 MessageType::Text(content) => content.formatted.as_ref(),
467 MessageType::Emote(content) => content.formatted.as_ref(),
468 MessageType::Notice(content) => content.formatted.as_ref(),
469
470 MessageType::Audio(content) => content.formatted.as_ref(),
471 MessageType::File(content) => content.formatted.as_ref(),
472 MessageType::Image(content) => content.formatted.as_ref(),
473 MessageType::Video(content) => content.formatted.as_ref(),
474 _ => None,
475 };
476
477 if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted {
478 Some(parse_matrix_html(body.as_str()))
471479 } else {
472480 None
473481 }
474482 }
475483
484 pub fn filename(&self) -> Option<String> {
485 match self {
486 MessageEvent::Original(ev) => content_filename(&ev.content),
487 MessageEvent::Local(_, _, content) => content_filename(content),
488 _ => None,
489 }
490 }
491
476492 fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
477493 match self {
478494 MessageEvent::EncryptedOriginal(_) => return,
@@ -514,12 +530,12 @@ impl MessageEvent {
514530
515531/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
516532/// `[Attached <type>: <content>[ (<human readable file size>)]]`
517macro_rules! display_file_to_text {
518 ( $msgtype:ident, $content:expr ) => {
519 return Cow::Owned(format!(
533macro_rules! display_file_name {
534 ( $msgtype:ident, $content:expr ) => {{
535 Some(format!(
520536 "[Attached {}: {}{}]",
521537 stringify!($msgtype),
522 $content.body,
538 $content.filename(),
523539 $content
524540 .info
525541 .as_ref()
@@ -530,7 +546,39 @@ macro_rules! display_file_to_text {
530546 })
531547 .unwrap_or_else(String::new)
532548 ))
533 };
549 }};
550}
551
552/// Macro rule extraction the text caption of a File / Image / Audio / Video
553macro_rules! display_file_to_text {
554 ( $msgtype:ident, $content:expr ) => {{
555 if $content
556 .filename
557 .as_ref()
558 .is_none_or(|filename| *filename == $content.body)
559 {
560 return Cow::Borrowed("");
561 }
562 $content.body.as_str()
563 }};
564}
565
566fn content_filename(content: &RoomMessageEventContent) -> Option<String> {
567 match &content.msgtype {
568 MessageType::Audio(content) => {
569 display_file_name!(Audio, content)
570 },
571 MessageType::File(content) => {
572 display_file_name!(File, content)
573 },
574 MessageType::Image(content) => {
575 display_file_name!(Image, content)
576 },
577 MessageType::Video(content) => {
578 display_file_name!(Video, content)
579 },
580 _ => None,
581 }
534582}
535583
536584fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
@@ -542,16 +590,16 @@ fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
542590 MessageType::ServerNotice(content) => content.body.as_str(),
543591
544592 MessageType::Audio(content) => {
545 display_file_to_text!(Audio, content);
593 display_file_to_text!(Audio, content)
546594 },
547595 MessageType::File(content) => {
548 display_file_to_text!(File, content);
596 display_file_to_text!(File, content)
549597 },
550598 MessageType::Image(content) => {
551 display_file_to_text!(Image, content);
599 display_file_to_text!(Image, content)
552600 },
553601 MessageType::Video(content) => {
554 display_file_to_text!(Video, content);
602 display_file_to_text!(Video, content)
555603 },
556604 _ => content.body(),
557605 };
@@ -1100,41 +1148,48 @@ impl Message {
11001148 settings: &'a ApplicationSettings,
11011149 previews: &'a PreviewManager,
11021150 ) -> (Text<'a>, Option<&'a Protocol>) {
1103 if let Some(html) = &self.html {
1104 (html.to_text(width, style, settings), None)
1151 let mut proto = None;
1152 let placeholder = match self.image_preview.as_ref().and_then(|source| previews.get(source))
1153 {
1154 None => None,
1155 Some(ImageStatus::Queued(image_preview_size)) => {
1156 placeholder_frame(Some("Queued..."), width, image_preview_size)
1157 },
1158 Some(ImageStatus::Downloading(image_preview_size)) => {
1159 placeholder_frame(Some("Downloading..."), width, image_preview_size)
1160 },
1161 Some(ImageStatus::Loaded(backend)) => {
1162 proto = Some(backend);
1163 placeholder_frame(Some("No Space..."), width, &backend.area().into())
1164 },
1165 Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")),
1166 };
1167
1168 let mut text = if let Some(placeholder) = placeholder {
1169 wrapped_text(placeholder, width, style)
11051170 } else {
1106 let mut msg = self.event.body();
1107 if settings.tunables.message_shortcode_display {
1108 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1109 }
1171 Default::default()
1172 };
11101173
1174 if let Some(mut filename) = self.event.filename() {
11111175 if self.downloaded {
1112 msg.to_mut().push_str(" \u{2705}");
1176 filename.push_str(" \u{2705}");
11131177 }
11141178
1115 let mut proto = None;
1116 let placeholder =
1117 match self.image_preview.as_ref().and_then(|source| previews.get(source)) {
1118 None => None,
1119 Some(ImageStatus::Queued(image_preview_size)) => {
1120 placeholder_frame(Some("Queued..."), width, image_preview_size)
1121 },
1122 Some(ImageStatus::Downloading(image_preview_size)) => {
1123 placeholder_frame(Some("Downloading..."), width, image_preview_size)
1124 },
1125 Some(ImageStatus::Loaded(backend)) => {
1126 proto = Some(backend);
1127 placeholder_frame(Some("No Space..."), width, &backend.area().into())
1128 },
1129 Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")),
1130 };
1131
1132 if let Some(placeholder) = placeholder {
1133 msg.to_mut().insert_str(0, &placeholder);
1179 text = text + wrapped_text(filename, width, style);
1180 }
1181
1182 if let Some(html) = &self.html {
1183 text = text + html.to_text(width, style, settings);
1184 } else {
1185 let mut msg = self.event.body();
1186 if settings.tunables.message_shortcode_display {
1187 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
11341188 }
1189 text = text + wrapped_text(msg, width, style);
1190 };
11351191
1136 (wrapped_text(msg, width, style), proto)
1137 }
1192 (text, proto)
11381193 }
11391194
11401195 fn sender_span<'a>(
@@ -1490,79 +1545,79 @@ pub mod tests {
14901545 #[test]
14911546 fn test_display_attachment_size() {
14921547 assert_eq!(
1493 body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1548 content_filename(&RoomMessageEventContent::new(MessageType::Image(
14941549 ImageMessageEventContent::plain(
14951550 "Alt text".to_string(),
14961551 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
14971552 )
14981553 .info(Some(Box::default()))
14991554 ))),
1500 "[Attached Image: Alt text]".to_string()
1555 "[Attached Image: Alt text]".to_string().into()
15011556 );
15021557
15031558 let mut info = ImageInfo::default();
15041559 info.size = Some(442630_u32.into());
15051560 assert_eq!(
1506 body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1561 content_filename(&RoomMessageEventContent::new(MessageType::Image(
15071562 ImageMessageEventContent::plain(
15081563 "Alt text".to_string(),
15091564 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
15101565 )
15111566 .info(Some(Box::new(info)))
15121567 ))),
1513 "[Attached Image: Alt text (442.63 kB)]".to_string()
1568 "[Attached Image: Alt text (442.63 kB)]".to_string().into()
15141569 );
15151570
15161571 let mut info = ImageInfo::default();
15171572 info.size = Some(12_u32.into());
15181573 assert_eq!(
1519 body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1574 content_filename(&RoomMessageEventContent::new(MessageType::Image(
15201575 ImageMessageEventContent::plain(
15211576 "Alt text".to_string(),
15221577 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
15231578 )
15241579 .info(Some(Box::new(info)))
15251580 ))),
1526 "[Attached Image: Alt text (12 B)]".to_string()
1581 "[Attached Image: Alt text (12 B)]".to_string().into()
15271582 );
15281583
15291584 let mut info = AudioInfo::default();
15301585 info.size = Some(4294967295_u32.into());
15311586 assert_eq!(
1532 body_cow_content(&RoomMessageEventContent::new(MessageType::Audio(
1587 content_filename(&RoomMessageEventContent::new(MessageType::Audio(
15331588 AudioMessageEventContent::plain(
15341589 "Alt text".to_string(),
15351590 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
15361591 )
15371592 .info(Some(Box::new(info)))
15381593 ))),
1539 "[Attached Audio: Alt text (4.29 GB)]".to_string()
1594 "[Attached Audio: Alt text (4.29 GB)]".to_string().into()
15401595 );
15411596
15421597 let mut info = FileInfo::default();
15431598 info.size = Some(4426300_u32.into());
15441599 assert_eq!(
1545 body_cow_content(&RoomMessageEventContent::new(MessageType::File(
1600 content_filename(&RoomMessageEventContent::new(MessageType::File(
15461601 FileMessageEventContent::plain(
15471602 "Alt text".to_string(),
15481603 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
15491604 )
15501605 .info(Some(Box::new(info)))
15511606 ))),
1552 "[Attached File: Alt text (4.43 MB)]".to_string()
1607 "[Attached File: Alt text (4.43 MB)]".to_string().into()
15531608 );
15541609
15551610 let mut info = VideoInfo::default();
15561611 info.size = Some(44000_u32.into());
15571612 assert_eq!(
1558 body_cow_content(&RoomMessageEventContent::new(MessageType::Video(
1613 content_filename(&RoomMessageEventContent::new(MessageType::Video(
15591614 VideoMessageEventContent::plain(
15601615 "Alt text".to_string(),
15611616 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
15621617 )
15631618 .info(Some(Box::new(info)))
15641619 ))),
1565 "[Attached Video: Alt text (44 kB)]".to_string()
1620 "[Attached Video: Alt text (44 kB)]".to_string().into()
15661621 );
15671622 }
15681623}
src/windows/room/chat.rs +126 −12
@@ -1,5 +1,6 @@
11//! Window for Matrix rooms
22use std::borrow::Cow;
3use std::convert::TryInto;
34use std::ffi::{OsStr, OsString};
45use std::fs;
56use std::ops::Deref;
@@ -7,6 +8,8 @@ use std::path::{Path, PathBuf};
78
89use edit::Builder;
910use edit::edit_with_builder as external_edit;
11use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
12use matrix_sdk::room::reply::{EnforceThread, Reply};
1013use modalkit::editing::store::RegisterError;
1114use std::process::Command;
1215use tokio;
@@ -42,7 +45,7 @@ use ratatui::{
4245 widgets::{Paragraph, StatefulWidget, Widget},
4346};
4447
45use modalkit::keybindings::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo};
48use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem, PromptYesNo};
4649
4750use modalkit_ratatui::{
4851 PromptActions,
@@ -87,7 +90,14 @@ use crate::base::{
8790};
8891
8992use crate::config::EncryptionIndicatorLocation;
90use crate::message::{MessageEvent, MessageId, MessageKey, TreeGenState, text_to_message};
93use crate::message::{
94 MessageEvent,
95 MessageId,
96 MessageKey,
97 TreeGenState,
98 text_to_message,
99 text_to_text_message_event_content,
100};
91101use crate::worker::Requester;
92102
93103use super::scrollback::{Scrollback, ScrollbackState};
@@ -562,6 +572,49 @@ impl ChatState {
562572 }
563573 }
564574
575 /// Generate a [`Reply`] setting thread info and reply_to (if `set_reply` is true)
576 fn generate_reply_info(&self, info: &RoomInfo, set_reply: bool) -> Option<Reply> {
577 let thread_last = self.scrollback.thread().and_then(|id| info.get_thread_last(id));
578
579 let (event_id, enforce_thread) = if let Some(last) = thread_last {
580 if let Some(m) = self.get_reply_to(info) &&
581 set_reply
582 {
583 // thread reply
584 (m.event_id.to_owned(), EnforceThread::Threaded(ReplyWithinThread::Yes))
585 } else {
586 // thread message
587 (last.event_id.to_owned(), EnforceThread::Threaded(ReplyWithinThread::No))
588 }
589 } else if let Some(m) = self.get_reply_to(info) &&
590 set_reply
591 {
592 // normal reply in main timeline:
593 (m.event_id.to_owned(), EnforceThread::Unthreaded)
594 } else {
595 // not any kind of reply:
596 return None;
597 };
598
599 Some(Reply {
600 add_mentions: AddMentions::No,
601 event_id,
602 enforce_thread,
603 })
604 }
605
606 /// Generate an attachment for this room based on the current message bar state.
607 fn generate_attachment_config(&self, info: &RoomInfo, add_caption: bool) -> AttachmentConfig {
608 let mut config = AttachmentConfig::new();
609 config.caption = add_caption
610 .then(|| self.tbox.get())
611 .filter(|c| !c.is_blank())
612 .map(|c| c.trim_end().to_string())
613 .and_then(text_to_text_message_event_content);
614 config.reply = self.generate_reply_info(info, add_caption);
615 config
616 }
617
565618 pub async fn send_command(
566619 &mut self,
567620 act: SendAction,
@@ -655,7 +708,28 @@ impl ChatState {
655708 // Reset message bar state now that it's been sent.
656709 self.reset();
657710 },
658 SendAction::Upload(file) => {
711 SendAction::Upload(file, add_caption) => {
712 let caption = self.tbox.get();
713
714 if add_caption.is_none() &&
715 (!caption.is_blank() || self.get_reply_to(info).is_some())
716 {
717 let msg = "Would you like to use the message bar as a caption?";
718
719 let yes_act = SendAction::Upload(file.clone(), Some(true));
720 let no_act = SendAction::Upload(file, Some(false));
721
722 let yes_choice =
723 MultiChoiceItem::new('y', msg, vec![IambAction::from(yes_act).into()]);
724 let no_choice =
725 MultiChoiceItem::new('n', "", vec![IambAction::from(no_act).into()]);
726
727 let prompt = MultiChoice::new(vec![yes_choice, no_choice]);
728 let prompt = Box::new(prompt);
729
730 return Err(UIError::NeedConfirm(prompt));
731 }
732
659733 let path = Path::new(file.as_str());
660734 let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
661735
@@ -664,14 +738,20 @@ impl ChatState {
664738 .file_name()
665739 .map(OsStr::to_string_lossy)
666740 .unwrap_or_else(|| Cow::from("Attachment"));
667 let config = AttachmentConfig::new();
741
742 let add_caption = add_caption.unwrap_or(false);
743 let config = self.generate_attachment_config(info, add_caption);
668744
669745 room.send_queue()
670746 .send_attachment(name.as_ref(), mime, bytes, config)
671747 .await
672748 .map_err(IambError::from)?;
749
750 if add_caption {
751 self.reset();
752 }
673753 },
674 SendAction::UploadImage(width, height, bytes) => {
754 SendAction::UploadImage(width, height, bytes, add_caption) => {
675755 // Convert to png because arboard does not give us the mime type.
676756 let bytes =
677757 image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned())
@@ -684,14 +764,23 @@ impl ChatState {
684764 Ok(buff.into_inner())
685765 })?;
686766 let mime = mime::IMAGE_PNG;
687
688767 let name = "Clipboard.png";
689 let config = AttachmentConfig::new();
768
769 let mut config = self.generate_attachment_config(info, add_caption);
770 config.info = Some(AttachmentInfo::Image(BaseImageInfo {
771 height: height.try_into().ok(),
772 width: width.try_into().ok(),
773 ..Default::default()
774 }));
690775
691776 room.send_queue()
692777 .send_attachment(name, mime, bytes, config)
693778 .await
694779 .map_err(IambError::from)?;
780
781 if add_caption {
782 self.reset();
783 }
695784 },
696785 }
697786
@@ -852,11 +941,36 @@ impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
852941 delegate!(self, w => w.editor_command(act, ctx, store))
853942 },
854943 Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
855 let msg = "Do you really want to upload the image from your system clipboard?";
856 let send =
857 IambAction::Send(SendAction::UploadImage(data.width, data.height, data.bytes));
858 let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
859 let prompt = Box::new(prompt);
944 let info = store.application.rooms.get_or_default(self.id().to_owned());
945 let prompt = if self.tbox.get().is_blank() && self.get_reply_to(info).is_none() {
946 let msg = "Do you really want to upload the image from your system clipboard?";
947 let send = IambAction::Send(SendAction::UploadImage(
948 data.width,
949 data.height,
950 data.bytes,
951 false,
952 ));
953 let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
954 Box::new(prompt) as Box<dyn Dialog<_>>
955 } else {
956 let msg_c = "Upload clipboard image with message bar as caption";
957 let act_c =
958 SendAction::UploadImage(data.width, data.height, data.bytes.clone(), true);
959 let choice_c =
960 MultiChoiceItem::new('c', msg_c, vec![IambAction::from(act_c).into()]);
961
962 let msg_y = "Upload clipboard image without caption";
963 let act_y =
964 SendAction::UploadImage(data.width, data.height, data.bytes.clone(), false);
965 let choice_y =
966 MultiChoiceItem::new('y', msg_y, vec![IambAction::from(act_y).into()]);
967
968 let msg_n = "Do not upload clipboard image";
969 let choice_n = MultiChoiceItem::new('n', msg_n, vec![Action::NoOp]);
970
971 let prompt = MultiChoice::new(vec![choice_c, choice_y, choice_n]);
972 Box::new(prompt) as Box<dyn Dialog<_>>
973 };
860974
861975 Err(EditError::NeedConfirm(prompt))
862976 },