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 {
491 SubmitFromEditor, 491 SubmitFromEditor,
492 492
493 /// Upload a file. 493 /// 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>),
495 498
496 /// Upload the image data. 499 /// 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),
498} 503}
499 504
500/// An action performed against the user's homeserver. 505/// 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 {
675 return Result::Err(CommandError::InvalidArgument); 675 return Result::Err(CommandError::InvalidArgument);
676 } 676 }
677 677
678 let sact = SendAction::Upload(args.remove(0)); 678 let sact = SendAction::Upload(args.remove(0), None);
679 let iact = IambAction::from(sact); 679 let iact = IambAction::from(sact);
680 let step = CommandStep::Continue(iact.into(), ctx.context.clone()); 680 let step = CommandStep::Continue(iact.into(), ctx.context.clone());
681 681
src/message/compose.rs +28
@@ -180,6 +180,34 @@ pub fn text_to_message(input: String) -> RoomMessageEventContent {
180 RoomMessageEventContent::new(msg) 180 RoomMessageEventContent::new(msg)
181} 181}
182 182
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
183#[cfg(test)] 211#[cfg(test)]
184pub mod tests { 212pub mod tests {
185 use super::*; 213 use super::*;
src/message/mod.rs +111 −56
@@ -73,7 +73,7 @@ mod html;
73mod printer; 73mod printer;
74mod state; 74mod state;
75 75
76pub use self::compose::text_to_message; 76pub use self::compose::{text_to_message, text_to_text_message_event_content};
77use self::state::{body_cow_state, html_state}; 77use self::state::{body_cow_state, html_state};
78pub use html::TreeGenState; 78pub use html::TreeGenState;
79 79
@@ -462,17 +462,33 @@ impl MessageEvent {
462 MessageEvent::Local(_, _, content) => content, 462 MessageEvent::Local(_, _, content) => content,
463 }; 463 };
464 464
465 if let MessageType::Text(content) = &content.msgtype { 465 let formatted = match &content.msgtype {
466 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted { 466 MessageType::Text(content) => content.formatted.as_ref(),
467 Some(parse_matrix_html(body.as_str())) 467 MessageType::Emote(content) => content.formatted.as_ref(),
468 } else { 468 MessageType::Notice(content) => content.formatted.as_ref(),
469 None 469
470 } 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()))
471 } else { 479 } else {
472 None 480 None
473 } 481 }
474 } 482 }
475 483
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
476 fn redact(&mut self, redaction: SyncRoomRedactionEvent) { 492 fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
477 match self { 493 match self {
478 MessageEvent::EncryptedOriginal(_) => return, 494 MessageEvent::EncryptedOriginal(_) => return,
@@ -514,12 +530,12 @@ impl MessageEvent {
514 530
515/// Macro rule converting a File / Image / Audio / Video to its text content with the shape: 531/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
516/// `[Attached <type>: <content>[ (<human readable file size>)]]` 532/// `[Attached <type>: <content>[ (<human readable file size>)]]`
517macro_rules! display_file_to_text { 533macro_rules! display_file_name {
518 ( $msgtype:ident, $content:expr ) => { 534 ( $msgtype:ident, $content:expr ) => {{
519 return Cow::Owned(format!( 535 Some(format!(
520 "[Attached {}: {}{}]", 536 "[Attached {}: {}{}]",
521 stringify!($msgtype), 537 stringify!($msgtype),
522 $content.body, 538 $content.filename(),
523 $content 539 $content
524 .info 540 .info
525 .as_ref() 541 .as_ref()
@@ -530,7 +546,39 @@ macro_rules! display_file_to_text {
530 }) 546 })
531 .unwrap_or_else(String::new) 547 .unwrap_or_else(String::new)
532 )) 548 ))
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 }
534} 582}
535 583
536fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> { 584fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
@@ -542,16 +590,16 @@ fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
542 MessageType::ServerNotice(content) => content.body.as_str(), 590 MessageType::ServerNotice(content) => content.body.as_str(),
543 591
544 MessageType::Audio(content) => { 592 MessageType::Audio(content) => {
545 display_file_to_text!(Audio, content); 593 display_file_to_text!(Audio, content)
546 }, 594 },
547 MessageType::File(content) => { 595 MessageType::File(content) => {
548 display_file_to_text!(File, content); 596 display_file_to_text!(File, content)
549 }, 597 },
550 MessageType::Image(content) => { 598 MessageType::Image(content) => {
551 display_file_to_text!(Image, content); 599 display_file_to_text!(Image, content)
552 }, 600 },
553 MessageType::Video(content) => { 601 MessageType::Video(content) => {
554 display_file_to_text!(Video, content); 602 display_file_to_text!(Video, content)
555 }, 603 },
556 _ => content.body(), 604 _ => content.body(),
557 }; 605 };
@@ -1100,41 +1148,48 @@ impl Message {
1100 settings: &'a ApplicationSettings, 1148 settings: &'a ApplicationSettings,
1101 previews: &'a PreviewManager, 1149 previews: &'a PreviewManager,
1102 ) -> (Text<'a>, Option<&'a Protocol>) { 1150 ) -> (Text<'a>, Option<&'a Protocol>) {
1103 if let Some(html) = &self.html { 1151 let mut proto = None;
1104 (html.to_text(width, style, settings), 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)
1105 } else { 1170 } else {
1106 let mut msg = self.event.body(); 1171 Default::default()
1107 if settings.tunables.message_shortcode_display { 1172 };
1108 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1109 }
1110 1173
1174 if let Some(mut filename) = self.event.filename() {
1111 if self.downloaded { 1175 if self.downloaded {
1112 msg.to_mut().push_str(" \u{2705}"); 1176 filename.push_str(" \u{2705}");
1113 } 1177 }
1114 1178
1115 let mut proto = None; 1179 text = text + wrapped_text(filename, width, style);
1116 let placeholder = 1180 }
1117 match self.image_preview.as_ref().and_then(|source| previews.get(source)) { 1181
1118 None => None, 1182 if let Some(html) = &self.html {
1119 Some(ImageStatus::Queued(image_preview_size)) => { 1183 text = text + html.to_text(width, style, settings);
1120 placeholder_frame(Some("Queued..."), width, image_preview_size) 1184 } else {
1121 }, 1185 let mut msg = self.event.body();
1122 Some(ImageStatus::Downloading(image_preview_size)) => { 1186 if settings.tunables.message_shortcode_display {
1123 placeholder_frame(Some("Downloading..."), width, image_preview_size) 1187 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
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);
1134 } 1188 }
1189 text = text + wrapped_text(msg, width, style);
1190 };
1135 1191
1136 (wrapped_text(msg, width, style), proto) 1192 (text, proto)
1137 }
1138 } 1193 }
1139 1194
1140 fn sender_span<'a>( 1195 fn sender_span<'a>(
@@ -1490,79 +1545,79 @@ pub mod tests {
1490 #[test] 1545 #[test]
1491 fn test_display_attachment_size() { 1546 fn test_display_attachment_size() {
1492 assert_eq!( 1547 assert_eq!(
1493 body_cow_content(&RoomMessageEventContent::new(MessageType::Image( 1548 content_filename(&RoomMessageEventContent::new(MessageType::Image(
1494 ImageMessageEventContent::plain( 1549 ImageMessageEventContent::plain(
1495 "Alt text".to_string(), 1550 "Alt text".to_string(),
1496 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() 1551 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1497 ) 1552 )
1498 .info(Some(Box::default())) 1553 .info(Some(Box::default()))
1499 ))), 1554 ))),
1500 "[Attached Image: Alt text]".to_string() 1555 "[Attached Image: Alt text]".to_string().into()
1501 ); 1556 );
1502 1557
1503 let mut info = ImageInfo::default(); 1558 let mut info = ImageInfo::default();
1504 info.size = Some(442630_u32.into()); 1559 info.size = Some(442630_u32.into());
1505 assert_eq!( 1560 assert_eq!(
1506 body_cow_content(&RoomMessageEventContent::new(MessageType::Image( 1561 content_filename(&RoomMessageEventContent::new(MessageType::Image(
1507 ImageMessageEventContent::plain( 1562 ImageMessageEventContent::plain(
1508 "Alt text".to_string(), 1563 "Alt text".to_string(),
1509 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() 1564 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1510 ) 1565 )
1511 .info(Some(Box::new(info))) 1566 .info(Some(Box::new(info)))
1512 ))), 1567 ))),
1513 "[Attached Image: Alt text (442.63 kB)]".to_string() 1568 "[Attached Image: Alt text (442.63 kB)]".to_string().into()
1514 ); 1569 );
1515 1570
1516 let mut info = ImageInfo::default(); 1571 let mut info = ImageInfo::default();
1517 info.size = Some(12_u32.into()); 1572 info.size = Some(12_u32.into());
1518 assert_eq!( 1573 assert_eq!(
1519 body_cow_content(&RoomMessageEventContent::new(MessageType::Image( 1574 content_filename(&RoomMessageEventContent::new(MessageType::Image(
1520 ImageMessageEventContent::plain( 1575 ImageMessageEventContent::plain(
1521 "Alt text".to_string(), 1576 "Alt text".to_string(),
1522 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() 1577 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1523 ) 1578 )
1524 .info(Some(Box::new(info))) 1579 .info(Some(Box::new(info)))
1525 ))), 1580 ))),
1526 "[Attached Image: Alt text (12 B)]".to_string() 1581 "[Attached Image: Alt text (12 B)]".to_string().into()
1527 ); 1582 );
1528 1583
1529 let mut info = AudioInfo::default(); 1584 let mut info = AudioInfo::default();
1530 info.size = Some(4294967295_u32.into()); 1585 info.size = Some(4294967295_u32.into());
1531 assert_eq!( 1586 assert_eq!(
1532 body_cow_content(&RoomMessageEventContent::new(MessageType::Audio( 1587 content_filename(&RoomMessageEventContent::new(MessageType::Audio(
1533 AudioMessageEventContent::plain( 1588 AudioMessageEventContent::plain(
1534 "Alt text".to_string(), 1589 "Alt text".to_string(),
1535 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() 1590 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1536 ) 1591 )
1537 .info(Some(Box::new(info))) 1592 .info(Some(Box::new(info)))
1538 ))), 1593 ))),
1539 "[Attached Audio: Alt text (4.29 GB)]".to_string() 1594 "[Attached Audio: Alt text (4.29 GB)]".to_string().into()
1540 ); 1595 );
1541 1596
1542 let mut info = FileInfo::default(); 1597 let mut info = FileInfo::default();
1543 info.size = Some(4426300_u32.into()); 1598 info.size = Some(4426300_u32.into());
1544 assert_eq!( 1599 assert_eq!(
1545 body_cow_content(&RoomMessageEventContent::new(MessageType::File( 1600 content_filename(&RoomMessageEventContent::new(MessageType::File(
1546 FileMessageEventContent::plain( 1601 FileMessageEventContent::plain(
1547 "Alt text".to_string(), 1602 "Alt text".to_string(),
1548 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() 1603 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1549 ) 1604 )
1550 .info(Some(Box::new(info))) 1605 .info(Some(Box::new(info)))
1551 ))), 1606 ))),
1552 "[Attached File: Alt text (4.43 MB)]".to_string() 1607 "[Attached File: Alt text (4.43 MB)]".to_string().into()
1553 ); 1608 );
1554 1609
1555 let mut info = VideoInfo::default(); 1610 let mut info = VideoInfo::default();
1556 info.size = Some(44000_u32.into()); 1611 info.size = Some(44000_u32.into());
1557 assert_eq!( 1612 assert_eq!(
1558 body_cow_content(&RoomMessageEventContent::new(MessageType::Video( 1613 content_filename(&RoomMessageEventContent::new(MessageType::Video(
1559 VideoMessageEventContent::plain( 1614 VideoMessageEventContent::plain(
1560 "Alt text".to_string(), 1615 "Alt text".to_string(),
1561 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() 1616 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1562 ) 1617 )
1563 .info(Some(Box::new(info))) 1618 .info(Some(Box::new(info)))
1564 ))), 1619 ))),
1565 "[Attached Video: Alt text (44 kB)]".to_string() 1620 "[Attached Video: Alt text (44 kB)]".to_string().into()
1566 ); 1621 );
1567 } 1622 }
1568} 1623}
src/windows/room/chat.rs +126 −12
@@ -1,5 +1,6 @@
1//! Window for Matrix rooms 1//! Window for Matrix rooms
2use std::borrow::Cow; 2use std::borrow::Cow;
3use std::convert::TryInto;
3use std::ffi::{OsStr, OsString}; 4use std::ffi::{OsStr, OsString};
4use std::fs; 5use std::fs;
5use std::ops::Deref; 6use std::ops::Deref;
@@ -7,6 +8,8 @@ use std::path::{Path, PathBuf};
7 8
8use edit::Builder; 9use edit::Builder;
9use edit::edit_with_builder as external_edit; 10use edit::edit_with_builder as external_edit;
11use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
12use matrix_sdk::room::reply::{EnforceThread, Reply};
10use modalkit::editing::store::RegisterError; 13use modalkit::editing::store::RegisterError;
11use std::process::Command; 14use std::process::Command;
12use tokio; 15use tokio;
@@ -42,7 +45,7 @@ use ratatui::{
42 widgets::{Paragraph, StatefulWidget, Widget}, 45 widgets::{Paragraph, StatefulWidget, Widget},
43}; 46};
44 47
45use modalkit::keybindings::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo}; 48use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem, PromptYesNo};
46 49
47use modalkit_ratatui::{ 50use modalkit_ratatui::{
48 PromptActions, 51 PromptActions,
@@ -87,7 +90,14 @@ use crate::base::{
87}; 90};
88 91
89use crate::config::EncryptionIndicatorLocation; 92use 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};
91use crate::worker::Requester; 101use crate::worker::Requester;
92 102
93use super::scrollback::{Scrollback, ScrollbackState}; 103use super::scrollback::{Scrollback, ScrollbackState};
@@ -562,6 +572,49 @@ impl ChatState {
562 } 572 }
563 } 573 }
564 574
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
565 pub async fn send_command( 618 pub async fn send_command(
566 &mut self, 619 &mut self,
567 act: SendAction, 620 act: SendAction,
@@ -655,7 +708,28 @@ impl ChatState {
655 // Reset message bar state now that it's been sent. 708 // Reset message bar state now that it's been sent.
656 self.reset(); 709 self.reset();
657 }, 710 },
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
659 let path = Path::new(file.as_str()); 733 let path = Path::new(file.as_str());
660 let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM); 734 let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
661 735
@@ -664,14 +738,20 @@ impl ChatState {
664 .file_name() 738 .file_name()
665 .map(OsStr::to_string_lossy) 739 .map(OsStr::to_string_lossy)
666 .unwrap_or_else(|| Cow::from("Attachment")); 740 .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);
668 744
669 room.send_queue() 745 room.send_queue()
670 .send_attachment(name.as_ref(), mime, bytes, config) 746 .send_attachment(name.as_ref(), mime, bytes, config)
671 .await 747 .await
672 .map_err(IambError::from)?; 748 .map_err(IambError::from)?;
749
750 if add_caption {
751 self.reset();
752 }
673 }, 753 },
674 SendAction::UploadImage(width, height, bytes) => { 754 SendAction::UploadImage(width, height, bytes, add_caption) => {
675 // Convert to png because arboard does not give us the mime type. 755 // Convert to png because arboard does not give us the mime type.
676 let bytes = 756 let bytes =
677 image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned()) 757 image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned())
@@ -684,14 +764,23 @@ impl ChatState {
684 Ok(buff.into_inner()) 764 Ok(buff.into_inner())
685 })?; 765 })?;
686 let mime = mime::IMAGE_PNG; 766 let mime = mime::IMAGE_PNG;
687
688 let name = "Clipboard.png"; 767 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 }));
690 775
691 room.send_queue() 776 room.send_queue()
692 .send_attachment(name, mime, bytes, config) 777 .send_attachment(name, mime, bytes, config)
693 .await 778 .await
694 .map_err(IambError::from)?; 779 .map_err(IambError::from)?;
780
781 if add_caption {
782 self.reset();
783 }
695 }, 784 },
696 } 785 }
697 786
@@ -852,11 +941,36 @@ impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
852 delegate!(self, w => w.editor_command(act, ctx, store)) 941 delegate!(self, w => w.editor_command(act, ctx, store))
853 }, 942 },
854 Err(EditError::Register(RegisterError::ClipboardImage(data))) => { 943 Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
855 let msg = "Do you really want to upload the image from your system clipboard?"; 944 let info = store.application.rooms.get_or_default(self.id().to_owned());
856 let send = 945 let prompt = if self.tbox.get().is_blank() && self.get_reply_to(info).is_none() {
857 IambAction::Send(SendAction::UploadImage(data.width, data.height, data.bytes)); 946 let msg = "Do you really want to upload the image from your system clipboard?";
858 let prompt = PromptYesNo::new(msg, vec![Action::from(send)]); 947 let send = IambAction::Send(SendAction::UploadImage(
859 let prompt = Box::new(prompt); 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 };
860 974
861 Err(EditError::NeedConfirm(prompt)) 975 Err(EditError::NeedConfirm(prompt))
862 }, 976 },