Commit a97c3c9f3c
Unregistered key
Layout: unified · split
src/base.rs +51 −47
| @@ -1768,6 +1768,24 @@ impl RoomInfo { | |||
| 1768 | self.set_implicit_receipt(sender, event_id); | 1768 | self.set_implicit_receipt(sender, event_id); |
| 1769 | } | 1769 | } |
| 1770 | 1770 | ||
| 1771 | /// Insert a message with a [`EventLocation::Message`] and previews. | ||
| 1772 | fn insert_msglike_with_preview( | ||
| 1773 | &mut self, | ||
| 1774 | event_id: OwnedEventId, | ||
| 1775 | thread_root: Option<OwnedEventId>, | ||
| 1776 | message: Message, | ||
| 1777 | settings: &ApplicationSettings, | ||
| 1778 | previews: &mut PreviewManager, | ||
| 1779 | ) { | ||
| 1780 | if settings.tunables.image_preview.enabled { | ||
| 1781 | for (source, kind) in message.image_previews() { | ||
| 1782 | previews.register_preview(settings, source, kind); | ||
| 1783 | } | ||
| 1784 | } | ||
| 1785 | |||
| 1786 | self.insert_msglike(event_id, thread_root, message); | ||
| 1787 | } | ||
| 1788 | |||
| 1771 | /// Insert a reaction to a message. | 1789 | /// Insert a reaction to a message. |
| 1772 | fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) { | 1790 | fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) { |
| 1773 | let MessageLikeEvent::Original(react) = react else { | 1791 | let MessageLikeEvent::Original(react) = react else { |
| @@ -1787,7 +1805,7 @@ impl RoomInfo { | |||
| 1787 | } | 1805 | } |
| 1788 | 1806 | ||
| 1789 | /// Insert a sticker | 1807 | /// Insert a sticker |
| 1790 | pub fn insert_sticker_with_preview( | 1808 | pub fn insert_sticker( |
| 1791 | &mut self, | 1809 | &mut self, |
| 1792 | sticker: StickerEvent, | 1810 | sticker: StickerEvent, |
| 1793 | settings: &ApplicationSettings, | 1811 | settings: &ApplicationSettings, |
| @@ -1806,17 +1824,7 @@ impl RoomInfo { | |||
| 1806 | _ => None, | 1824 | _ => None, |
| 1807 | }; | 1825 | }; |
| 1808 | 1826 | ||
| 1809 | if let MessageLikeEvent::Original(OriginalMessageLikeEvent { | 1827 | self.insert_msglike_with_preview(event_id, thread_root, sticker.into(), settings, previews); |
| 1810 | content: StickerEventContent { source, .. }, | ||
| 1811 | .. | ||
| 1812 | }) = &sticker && | ||
| 1813 | settings.tunables.image_preview.enabled | ||
| 1814 | { | ||
| 1815 | let source = source.clone().into(); | ||
| 1816 | previews.register_preview(settings, &source, PreviewKind::Message); | ||
| 1817 | } | ||
| 1818 | |||
| 1819 | self.insert_msglike(event_id, thread_root, sticker.into()); | ||
| 1820 | } | 1828 | } |
| 1821 | 1829 | ||
| 1822 | /// Insert a reaction to a message. | 1830 | /// Insert a reaction to a message. |
| @@ -1839,7 +1847,7 @@ impl RoomInfo { | |||
| 1839 | if settings.tunables.image_preview.enabled && | 1847 | if settings.tunables.image_preview.enabled && |
| 1840 | let Some(source) = source.as_ref() | 1848 | let Some(source) = source.as_ref() |
| 1841 | { | 1849 | { |
| 1842 | previews.register_preview(settings, source, PreviewKind::Reaction); | 1850 | previews.register_preview(settings, source, PreviewKind::Emoji); |
| 1843 | } | 1851 | } |
| 1844 | 1852 | ||
| 1845 | self.insert_reaction(react, source); | 1853 | self.insert_reaction(react, source); |
| @@ -2028,6 +2036,8 @@ impl RoomInfo { | |||
| 2028 | &mut self, | 2036 | &mut self, |
| 2029 | edit_msg: RoomMessageEvent, | 2037 | edit_msg: RoomMessageEvent, |
| 2030 | replacement: Replacement<RoomMessageEventContentWithoutRelation>, | 2038 | replacement: Replacement<RoomMessageEventContentWithoutRelation>, |
| 2039 | settings: &ApplicationSettings, | ||
| 2040 | previews: &mut PreviewManager, | ||
| 2031 | ) { | 2041 | ) { |
| 2032 | let RoomMessageEvent::Original(edit_msg) = edit_msg else { | 2042 | let RoomMessageEvent::Original(edit_msg) = edit_msg else { |
| 2033 | return; | 2043 | return; |
| @@ -2044,6 +2054,12 @@ impl RoomInfo { | |||
| 2044 | return; | 2054 | return; |
| 2045 | }; | 2055 | }; |
| 2046 | msg.insert_edit(edit_key.clone(), replacement.new_content); | 2056 | msg.insert_edit(edit_key.clone(), replacement.new_content); |
| 2057 | |||
| 2058 | if settings.tunables.image_preview.enabled { | ||
| 2059 | for (source, kind) in msg.image_previews() { | ||
| 2060 | previews.register_preview(settings, source, kind); | ||
| 2061 | } | ||
| 2062 | } | ||
| 2047 | } else { | 2063 | } else { |
| 2048 | // The edited message is not yet loaded | 2064 | // The edited message is not yet loaded |
| 2049 | let entry = self.unloaded_edits.entry(replacement.event_id.clone()); | 2065 | let entry = self.unloaded_edits.entry(replacement.event_id.clone()); |
| @@ -2075,44 +2091,28 @@ impl RoomInfo { | |||
| 2075 | self.insert_msglike(event_id, thread_root, msg.into()); | 2091 | self.insert_msglike(event_id, thread_root, msg.into()); |
| 2076 | } | 2092 | } |
| 2077 | 2093 | ||
| 2078 | /// Insert a new message. | 2094 | /// Insert a new message event, and prepare for image-preview if it has an image attachment. |
| 2079 | fn insert_message(&mut self, msg: RoomMessageEvent) { | 2095 | pub fn insert_message( |
| 2080 | let event_id = msg.event_id().to_owned(); | 2096 | &mut self, |
| 2081 | let thread_root = match msg.as_original().and_then(|ev| ev.content.relates_to.as_ref()) { | 2097 | ev: RoomMessageEvent, |
| 2098 | settings: &ApplicationSettings, | ||
| 2099 | previews: &mut PreviewManager, | ||
| 2100 | ) { | ||
| 2101 | let event_id = ev.event_id().to_owned(); | ||
| 2102 | let thread_root = match ev.as_original().and_then(|ev| ev.content.relates_to.as_ref()) { | ||
| 2082 | Some(Relation::Replacement(repl)) => { | 2103 | Some(Relation::Replacement(repl)) => { |
| 2083 | let repl = repl.to_owned(); | 2104 | let repl = repl.to_owned(); |
| 2084 | self.insert_edit(msg, repl); | 2105 | self.insert_edit(ev, repl, settings, previews); |
| 2085 | return; | 2106 | return; |
| 2086 | }, | 2107 | }, |
| 2087 | Some(Relation::Thread(Thread { event_id, .. })) => Some(event_id.to_owned()), | 2108 | Some(Relation::Thread(Thread { event_id, .. })) => Some(event_id.to_owned()), |
| 2088 | _ => None, | 2109 | _ => None, |
| 2089 | }; | 2110 | }; |
| 2090 | 2111 | let mut message: Message = ev.into(); | |
| 2091 | let mut message: Message = msg.into(); | ||
| 2092 | if let Some(edits) = self.unloaded_edits.remove(&event_id) { | 2112 | if let Some(edits) = self.unloaded_edits.remove(&event_id) { |
| 2093 | message.set_edits(edits); | 2113 | message.set_edits(edits); |
| 2094 | } | 2114 | } |
| 2095 | 2115 | self.insert_msglike_with_preview(event_id, thread_root, message, settings, previews); | |
| 2096 | self.insert_msglike(event_id, thread_root, message); | ||
| 2097 | } | ||
| 2098 | |||
| 2099 | /// Insert a new message event, and prepare for image-preview if it has an image attachment. | ||
| 2100 | pub fn insert_with_preview( | ||
| 2101 | &mut self, | ||
| 2102 | ev: RoomMessageEvent, | ||
| 2103 | settings: &ApplicationSettings, | ||
| 2104 | previews: &mut PreviewManager, | ||
| 2105 | ) { | ||
| 2106 | if let MessageLikeEvent::Original(OriginalMessageLikeEvent { | ||
| 2107 | content: RoomMessageEventContent { msgtype: MessageType::Image(c), .. }, | ||
| 2108 | .. | ||
| 2109 | }) = &ev && | ||
| 2110 | settings.tunables.image_preview.enabled | ||
| 2111 | { | ||
| 2112 | previews.register_preview(settings, &c.source, PreviewKind::Message) | ||
| 2113 | } | ||
| 2114 | |||
| 2115 | self.insert_message(ev); | ||
| 2116 | } | 2116 | } |
| 2117 | 2117 | ||
| 2118 | /// Indicates whether this room has unread messages. | 2118 | /// Indicates whether this room has unread messages. |
| @@ -3234,7 +3234,7 @@ pub mod tests { | |||
| 3234 | MSG5_KEY.clone(), | 3234 | MSG5_KEY.clone(), |
| 3235 | ); | 3235 | ); |
| 3236 | 3236 | ||
| 3237 | info.insert_with_preview(event, &settings, &mut previews); | 3237 | info.insert_message(event, &settings, &mut previews); |
| 3238 | 3238 | ||
| 3239 | assert_eq!( | 3239 | assert_eq!( |
| 3240 | info.user_receipts | 3240 | info.user_receipts |
| @@ -3266,8 +3266,8 @@ pub mod tests { | |||
| 3266 | MSG2_KEY.clone(), | 3266 | MSG2_KEY.clone(), |
| 3267 | ); | 3267 | ); |
| 3268 | 3268 | ||
| 3269 | info.insert_with_preview(newer, &settings, &mut previews); | 3269 | info.insert_message(newer, &settings, &mut previews); |
| 3270 | info.insert_with_preview(older, &settings, &mut previews); | 3270 | info.insert_message(older, &settings, &mut previews); |
| 3271 | 3271 | ||
| 3272 | assert_eq!( | 3272 | assert_eq!( |
| 3273 | info.user_receipts | 3273 | info.user_receipts |
| @@ -3314,6 +3314,8 @@ pub mod tests { | |||
| 3314 | 3314 | ||
| 3315 | #[test] | 3315 | #[test] |
| 3316 | fn test_explicit_receipt_does_not_move_implicit_receipt_backwards() { | 3316 | fn test_explicit_receipt_does_not_move_implicit_receipt_backwards() { |
| 3317 | let settings = mock_settings(); | ||
| 3318 | let mut previews = PreviewManager::new(&settings); | ||
| 3317 | let mut info = RoomInfo::default(); | 3319 | let mut info = RoomInfo::default(); |
| 3318 | let older = mock_room_message_event( | 3320 | let older = mock_room_message_event( |
| 3319 | RoomMessageEventContent::text_plain("older"), | 3321 | RoomMessageEventContent::text_plain("older"), |
| @@ -3326,8 +3328,8 @@ pub mod tests { | |||
| 3326 | MSG5_KEY.clone(), | 3328 | MSG5_KEY.clone(), |
| 3327 | ); | 3329 | ); |
| 3328 | 3330 | ||
| 3329 | info.insert_message(older); | 3331 | info.insert_message(older, &settings, &mut previews); |
| 3330 | info.insert_message(newer); | 3332 | info.insert_message(newer, &settings, &mut previews); |
| 3331 | info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone()); | 3333 | info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone()); |
| 3332 | 3334 | ||
| 3333 | assert_eq!( | 3335 | assert_eq!( |
| @@ -3340,6 +3342,8 @@ pub mod tests { | |||
| 3340 | 3342 | ||
| 3341 | #[test] | 3343 | #[test] |
| 3342 | fn test_implicit_receipt_waits_for_unloaded_explicit_receipt() { | 3344 | fn test_implicit_receipt_waits_for_unloaded_explicit_receipt() { |
| 3345 | let settings = mock_settings(); | ||
| 3346 | let mut previews = PreviewManager::new(&settings); | ||
| 3343 | let mut info = RoomInfo::default(); | 3347 | let mut info = RoomInfo::default(); |
| 3344 | info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG5_EVID.clone()); | 3348 | info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG5_EVID.clone()); |
| 3345 | let older = mock_room_message_event( | 3349 | let older = mock_room_message_event( |
| @@ -3348,7 +3352,7 @@ pub mod tests { | |||
| 3348 | MSG2_KEY.clone(), | 3352 | MSG2_KEY.clone(), |
| 3349 | ); | 3353 | ); |
| 3350 | 3354 | ||
| 3351 | info.insert_message(older); | 3355 | info.insert_message(older, &settings, &mut previews); |
| 3352 | 3356 | ||
| 3353 | assert_eq!( | 3357 | assert_eq!( |
| 3354 | info.user_receipts | 3358 | info.user_receipts |
src/message/html.rs +235 −36
| @@ -18,10 +18,14 @@ use html5ever::tendril::{StrTendril, TendrilSink}; | |||
| 18 | use html5ever::{local_name, ns}; | 18 | use html5ever::{local_name, ns}; |
| 19 | use markup5ever_rcdom::{Handle, NodeData, RcDom}; | 19 | use markup5ever_rcdom::{Handle, NodeData, RcDom}; |
| 20 | use matrix_sdk::OwnedServerName; | 20 | use matrix_sdk::OwnedServerName; |
| 21 | use matrix_sdk::ruma::OwnedMxcUri; | ||
| 22 | use matrix_sdk::ruma::events::room::ImageInfo; | ||
| 21 | 23 | ||
| 22 | use crate::message::printer::TextPrinter; | 24 | use crate::message::printer::TextPrinter; |
| 25 | use crate::message::{ProtocolPreview, placeholder_frame}; | ||
| 23 | use crate::prelude::*; | 26 | use crate::prelude::*; |
| 24 | use crate::util::{join_cell_text, space_text}; | 27 | use crate::preview::ImageStatus; |
| 28 | use crate::util::{join_cell_text, space_text, wrapped_text}; | ||
| 25 | 29 | ||
| 26 | /// Generate bullet points from a [ListStyle]. | 30 | /// Generate bullet points from a [ListStyle]. |
| 27 | pub struct BulletIterator { | 31 | pub struct BulletIterator { |
| @@ -101,6 +105,12 @@ impl TableRow { | |||
| 101 | } | 105 | } |
| 102 | } | 106 | } |
| 103 | 107 | ||
| 108 | pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { | ||
| 109 | for (_, cell) in &self.cells { | ||
| 110 | cell.image_previews(previews); | ||
| 111 | } | ||
| 112 | } | ||
| 113 | |||
| 104 | fn columns(&self) -> usize { | 114 | fn columns(&self) -> usize { |
| 105 | self.cells.len() | 115 | self.cells.len() |
| 106 | } | 116 | } |
| @@ -119,6 +129,12 @@ impl TableSection { | |||
| 119 | } | 129 | } |
| 120 | } | 130 | } |
| 121 | 131 | ||
| 132 | pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { | ||
| 133 | for row in &self.rows { | ||
| 134 | row.image_previews(previews); | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 122 | fn columns(&self) -> usize { | 138 | fn columns(&self) -> usize { |
| 123 | self.rows.iter().map(TableRow::columns).max().unwrap_or(0) | 139 | self.rows.iter().map(TableRow::columns).max().unwrap_or(0) |
| 124 | } | 140 | } |
| @@ -142,16 +158,16 @@ impl Table { | |||
| 142 | } | 158 | } |
| 143 | } | 159 | } |
| 144 | 160 | ||
| 145 | fn to_text<'a>( | 161 | pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { |
| 146 | &'a self, | 162 | for section in &self.sections { |
| 147 | width: usize, | 163 | section.image_previews(previews); |
| 148 | style: Style, | 164 | } |
| 149 | settings: &'a ApplicationSettings, | 165 | } |
| 150 | info: &'a RoomInfo, | 166 | |
| 151 | ) -> Text<'a> { | 167 | fn to_text<'a>(&'a self, printer: &TextPrinter<'a>, style: Style) -> Text<'a> { |
| 152 | let mut text = Text::default(); | 168 | let mut text = Text::default(); |
| 153 | let columns = self.columns(); | 169 | let columns = self.columns(); |
| 154 | let cell_total = width.saturating_sub(columns).saturating_sub(1); | 170 | let cell_total = printer.width().saturating_sub(columns).saturating_sub(1); |
| 155 | let cell_min = cell_total.checked_div(columns).unwrap_or(0); | 171 | let cell_min = cell_total.checked_div(columns).unwrap_or(0); |
| 156 | let mut cell_slop = cell_total - cell_min * columns; | 172 | let mut cell_slop = cell_total - cell_min * columns; |
| 157 | let cell_widths = (0..columns) | 173 | let cell_widths = (0..columns) |
| @@ -164,16 +180,14 @@ impl Table { | |||
| 164 | 180 | ||
| 165 | let mut nrows = 0; | 181 | let mut nrows = 0; |
| 166 | 182 | ||
| 167 | let line_style = style.patch(settings.theme.messages.table); | 183 | let line_style = style.patch(printer.settings.theme.messages.table); |
| 168 | let line = settings.theme.messages.table_line.to_table_set(); | 184 | let line = printer.settings.theme.messages.table_line.to_table_set(); |
| 169 | 185 | ||
| 170 | if let Some(caption) = &self.caption { | 186 | if let Some(caption) = &self.caption { |
| 171 | let subw = width.saturating_sub(6); | 187 | let mut printer = printer.sub(6).align(Alignment::Center); |
| 172 | let mut printer = | ||
| 173 | TextPrinter::new(subw, style, settings, info).align(Alignment::Center); | ||
| 174 | caption.print(&mut printer, style); | 188 | caption.print(&mut printer, style); |
| 175 | 189 | ||
| 176 | for mut line in printer.finish().lines { | 190 | for mut line in printer.finish().0.lines { |
| 177 | line.spans.insert(0, Span::styled(" ", style)); | 191 | line.spans.insert(0, Span::styled(" ", style)); |
| 178 | line.spans.push(Span::styled(" ", style)); | 192 | line.spans.push(Span::styled(" ", style)); |
| 179 | text.lines.push(line); | 193 | text.lines.push(line); |
| @@ -222,7 +236,7 @@ impl Table { | |||
| 222 | CellType::Data => style, | 236 | CellType::Data => style, |
| 223 | }; | 237 | }; |
| 224 | 238 | ||
| 225 | cell.to_text(*w, style, settings, info) | 239 | cell.to_text(*w, style, printer.settings, printer.info) |
| 226 | } else { | 240 | } else { |
| 227 | space_text(*w, style) | 241 | space_text(*w, style) |
| 228 | }; | 242 | }; |
| @@ -282,6 +296,49 @@ impl ThemeSelector { | |||
| 282 | } | 296 | } |
| 283 | } | 297 | } |
| 284 | 298 | ||
| 299 | #[derive(Debug, Clone)] | ||
| 300 | pub struct Image { | ||
| 301 | title: Option<String>, | ||
| 302 | alt: Option<String>, | ||
| 303 | width: Option<u16>, | ||
| 304 | height: Option<u16>, | ||
| 305 | src: Option<MediaSource>, | ||
| 306 | is_emote: bool, | ||
| 307 | } | ||
| 308 | |||
| 309 | impl Image { | ||
| 310 | pub fn new(src: MediaSource, info: Option<&ImageInfo>) -> Self { | ||
| 311 | let width = info | ||
| 312 | .and_then(|info| info.width) | ||
| 313 | .and_then(|width| u16::try_from(width).ok()); | ||
| 314 | let height = info | ||
| 315 | .and_then(|info| info.height) | ||
| 316 | .and_then(|height| u16::try_from(height).ok()); | ||
| 317 | |||
| 318 | Self { | ||
| 319 | src: Some(src), | ||
| 320 | width, | ||
| 321 | height, | ||
| 322 | |||
| 323 | title: None, | ||
| 324 | alt: None, | ||
| 325 | is_emote: false, | ||
| 326 | } | ||
| 327 | } | ||
| 328 | |||
| 329 | fn kind(&self) -> PreviewKind { | ||
| 330 | if self.is_emote { | ||
| 331 | return PreviewKind::Emoji; | ||
| 332 | } | ||
| 333 | |||
| 334 | PreviewKind::Custom(self.width, self.height) | ||
| 335 | } | ||
| 336 | |||
| 337 | fn preview<'a>(&self, previews: &'a PreviewManager) -> Option<&'a ImageStatus> { | ||
| 338 | self.src.as_ref().and_then(|src| previews.get(src, self.kind())) | ||
| 339 | } | ||
| 340 | } | ||
| 341 | |||
| 285 | /// A processed HTML element that we can render to the terminal. | 342 | /// A processed HTML element that we can render to the terminal. |
| 286 | #[derive(Debug, Clone)] | 343 | #[derive(Debug, Clone)] |
| 287 | pub enum StyleTreeNode { | 344 | pub enum StyleTreeNode { |
| @@ -291,7 +348,7 @@ pub enum StyleTreeNode { | |||
| 291 | #[allow(dead_code)] | 348 | #[allow(dead_code)] |
| 292 | Code(Box<StyleTreeNode>, Option<String>), | 349 | Code(Box<StyleTreeNode>, Option<String>), |
| 293 | Header(Box<StyleTreeNode>, usize), | 350 | Header(Box<StyleTreeNode>, usize), |
| 294 | Image(Option<String>), | 351 | Image(Image), |
| 295 | List(StyleTreeChildren, ListStyle), | 352 | List(StyleTreeChildren, ListStyle), |
| 296 | Paragraph(Box<StyleTreeNode>), | 353 | Paragraph(Box<StyleTreeNode>), |
| 297 | Pre(Box<StyleTreeNode>), | 354 | Pre(Box<StyleTreeNode>), |
| @@ -315,9 +372,9 @@ impl StyleTreeNode { | |||
| 315 | settings: &'a ApplicationSettings, | 372 | settings: &'a ApplicationSettings, |
| 316 | info: &'a RoomInfo, | 373 | info: &'a RoomInfo, |
| 317 | ) -> Text<'a> { | 374 | ) -> Text<'a> { |
| 318 | let mut printer = TextPrinter::new(width, style, settings, info); | 375 | let mut printer = TextPrinter::new(width, style, settings, info, None); |
| 319 | self.print(&mut printer, style); | 376 | self.print(&mut printer, style); |
| 320 | printer.finish() | 377 | printer.finish().0 |
| 321 | } | 378 | } |
| 322 | 379 | ||
| 323 | pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) { | 380 | pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) { |
| @@ -379,13 +436,52 @@ impl StyleTreeNode { | |||
| 379 | } | 436 | } |
| 380 | }, | 437 | }, |
| 381 | 438 | ||
| 382 | StyleTreeNode::Image(_) => {}, | 439 | StyleTreeNode::Image(..) => {}, |
| 383 | StyleTreeNode::Ruler => {}, | 440 | StyleTreeNode::Ruler => {}, |
| 384 | StyleTreeNode::Text(_) => {}, | 441 | StyleTreeNode::Text(_) => {}, |
| 385 | StyleTreeNode::Break => {}, | 442 | StyleTreeNode::Break => {}, |
| 386 | } | 443 | } |
| 387 | } | 444 | } |
| 388 | 445 | ||
| 446 | pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) { | ||
| 447 | match self { | ||
| 448 | StyleTreeNode::Image(img) => { | ||
| 449 | if let Some(source) = &img.src { | ||
| 450 | previews.push((source, img.kind())); | ||
| 451 | } | ||
| 452 | }, | ||
| 453 | |||
| 454 | StyleTreeNode::Blockquote(child) | | ||
| 455 | StyleTreeNode::Code(child, _) | | ||
| 456 | StyleTreeNode::Header(child, _) | | ||
| 457 | StyleTreeNode::Paragraph(child) | | ||
| 458 | StyleTreeNode::Pre(child) | | ||
| 459 | StyleTreeNode::Style(child, _) | | ||
| 460 | StyleTreeNode::Themed(child, _) => { | ||
| 461 | child.image_previews(previews); | ||
| 462 | }, | ||
| 463 | |||
| 464 | StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => { | ||
| 465 | for child in children { | ||
| 466 | child.image_previews(previews); | ||
| 467 | } | ||
| 468 | }, | ||
| 469 | |||
| 470 | StyleTreeNode::Table(table) => { | ||
| 471 | table.image_previews(previews); | ||
| 472 | }, | ||
| 473 | |||
| 474 | StyleTreeNode::Ruler | | ||
| 475 | StyleTreeNode::Text(..) | | ||
| 476 | StyleTreeNode::Break | | ||
| 477 | StyleTreeNode::Anchor(..) | | ||
| 478 | StyleTreeNode::RoomAlias(..) | | ||
| 479 | StyleTreeNode::RoomId(..) | | ||
| 480 | StyleTreeNode::UserId(..) | | ||
| 481 | StyleTreeNode::DisplayName(..) => {}, | ||
| 482 | } | ||
| 483 | } | ||
| 484 | |||
| 389 | pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) { | 485 | pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) { |
| 390 | let width = printer.width(); | 486 | let width = printer.width(); |
| 391 | 487 | ||
| @@ -406,7 +502,7 @@ impl StyleTreeNode { | |||
| 406 | let mut subp = printer.sub(3); | 502 | let mut subp = printer.sub(3); |
| 407 | child.print(&mut subp, style); | 503 | child.print(&mut subp, style); |
| 408 | 504 | ||
| 409 | for mut line in subp.finish() { | 505 | for mut line in subp.finish().0 { |
| 410 | line.spans.insert(0, Span::styled(" ", style)); | 506 | line.spans.insert(0, Span::styled(" ", style)); |
| 411 | line.spans.insert(0, Span::styled(quote, quote_style)); | 507 | line.spans.insert(0, Span::styled(quote, quote_style)); |
| 412 | line.spans.insert(0, Span::styled(" ", style)); | 508 | line.spans.insert(0, Span::styled(" ", style)); |
| @@ -432,11 +528,48 @@ impl StyleTreeNode { | |||
| 432 | printer.push_str(" ", style); | 528 | printer.push_str(" ", style); |
| 433 | child.print(printer, style); | 529 | child.print(printer, style); |
| 434 | }, | 530 | }, |
| 435 | StyleTreeNode::Image(None) => {}, | 531 | StyleTreeNode::Image(img @ Image { is_emote: true, .. }) => { |
| 436 | StyleTreeNode::Image(Some(alt)) => { | 532 | if let Some(previews) = printer.previews && |
| 533 | let Some(image) = img.preview(previews) && | ||
| 534 | let ImageStatus::Loaded(image) = image | ||
| 535 | { | ||
| 536 | printer.push_emoji(image, style); | ||
| 537 | } else { | ||
| 538 | let title = img.title.as_deref().unwrap_or("emote"); | ||
| 539 | printer.push_span_nobreak(Span::styled(format!(":{title}:"), style)); | ||
| 540 | } | ||
| 541 | }, | ||
| 542 | StyleTreeNode::Image(img) => { | ||
| 543 | let alt = img.alt.as_deref().or(img.title.as_deref()); | ||
| 544 | |||
| 545 | let mut proto = None; | ||
| 546 | let placeholder = match printer.previews.and_then(|previews| img.preview(previews)) | ||
| 547 | { | ||
| 548 | None => { | ||
| 549 | if let Some(alt) = alt { | ||
| 550 | format!("[Image Alt: {alt}]") | ||
| 551 | } else { | ||
| 552 | "[Image]".to_string() | ||
| 553 | } | ||
| 554 | }, | ||
| 555 | Some(ImageStatus::Queued(image_preview_size)) => { | ||
| 556 | placeholder_frame(Some("Queued..."), width, image_preview_size) | ||
| 557 | }, | ||
| 558 | Some(ImageStatus::Downloading(image_preview_size)) => { | ||
| 559 | placeholder_frame(Some("Downloading..."), width, image_preview_size) | ||
| 560 | }, | ||
| 561 | Some(ImageStatus::Loaded(backend)) => { | ||
| 562 | proto = Some(backend); | ||
| 563 | placeholder_frame(None, width, &backend.size()) | ||
| 564 | }, | ||
| 565 | Some(ImageStatus::Error(err)) => format!("[Image error: {err}]\n"), | ||
| 566 | }; | ||
| 567 | |||
| 437 | printer.commit(); | 568 | printer.commit(); |
| 438 | printer.push_str("Image Alt: ", style); | 569 | if let Some(proto) = proto { |
| 439 | printer.push_str(alt, style); | 570 | printer.push_image(proto); |
| 571 | } | ||
| 572 | printer.push_text(wrapped_text(placeholder, width, style)); | ||
| 440 | printer.commit(); | 573 | printer.commit(); |
| 441 | }, | 574 | }, |
| 442 | StyleTreeNode::List(children, lt) => { | 575 | StyleTreeNode::List(children, lt) => { |
| @@ -448,7 +581,7 @@ impl StyleTreeNode { | |||
| 448 | let mut bullet = bullets.next(); | 581 | let mut bullet = bullets.next(); |
| 449 | child.print(&mut subp, style); | 582 | child.print(&mut subp, style); |
| 450 | 583 | ||
| 451 | for mut line in subp.finish() { | 584 | for mut line in subp.finish().0 { |
| 452 | let leading = if let Some(bullet) = bullet.take() { | 585 | let leading = if let Some(bullet) = bullet.take() { |
| 453 | Span::styled(bullet, style) | 586 | Span::styled(bullet, style) |
| 454 | } else { | 587 | } else { |
| @@ -484,7 +617,7 @@ impl StyleTreeNode { | |||
| 484 | .into(), | 617 | .into(), |
| 485 | ); | 618 | ); |
| 486 | 619 | ||
| 487 | for mut line in subp.finish() { | 620 | for mut line in subp.finish().0 { |
| 488 | line.spans.insert(0, Span::styled(border.vertical_left, style)); | 621 | line.spans.insert(0, Span::styled(border.vertical_left, style)); |
| 489 | line.spans.push(Span::styled(border.vertical_right, style)); | 622 | line.spans.push(Span::styled(border.vertical_right, style)); |
| 490 | printer.push_line(line); | 623 | printer.push_line(line); |
| @@ -510,7 +643,7 @@ impl StyleTreeNode { | |||
| 510 | } | 643 | } |
| 511 | }, | 644 | }, |
| 512 | StyleTreeNode::Table(table) => { | 645 | StyleTreeNode::Table(table) => { |
| 513 | let text = table.to_text(width, style, printer.settings, printer.info); | 646 | let text = table.to_text(printer, style); |
| 514 | printer.push_text(text); | 647 | printer.push_text(text); |
| 515 | }, | 648 | }, |
| 516 | StyleTreeNode::Break => { | 649 | StyleTreeNode::Break => { |
| @@ -597,6 +730,16 @@ impl StyleTree { | |||
| 597 | return links; | 730 | return links; |
| 598 | } | 731 | } |
| 599 | 732 | ||
| 733 | pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> { | ||
| 734 | let mut previews = vec![]; | ||
| 735 | |||
| 736 | for child in &self.children { | ||
| 737 | child.image_previews(&mut previews); | ||
| 738 | } | ||
| 739 | |||
| 740 | return previews; | ||
| 741 | } | ||
| 742 | |||
| 600 | pub fn to_text<'a>( | 743 | pub fn to_text<'a>( |
| 601 | &'a self, | 744 | &'a self, |
| 602 | width: usize, | 745 | width: usize, |
| @@ -604,7 +747,25 @@ impl StyleTree { | |||
| 604 | settings: &'a ApplicationSettings, | 747 | settings: &'a ApplicationSettings, |
| 605 | info: &'a RoomInfo, | 748 | info: &'a RoomInfo, |
| 606 | ) -> Text<'a> { | 749 | ) -> Text<'a> { |
| 607 | let mut printer = TextPrinter::new(width, style, settings, info); | 750 | let mut printer = TextPrinter::new(width, style, settings, info, None); |
| 751 | |||
| 752 | for child in self.children.iter() { | ||
| 753 | child.print(&mut printer, style); | ||
| 754 | } | ||
| 755 | |||
| 756 | printer.finish().0 | ||
| 757 | } | ||
| 758 | |||
| 759 | /// The images are in the format `(protocol, x, y)` | ||
| 760 | pub fn render<'a>( | ||
| 761 | &'a self, | ||
| 762 | width: usize, | ||
| 763 | style: Style, | ||
| 764 | settings: &'a ApplicationSettings, | ||
| 765 | info: &'a RoomInfo, | ||
| 766 | previews: &'a PreviewManager, | ||
| 767 | ) -> (Text<'a>, Vec<ProtocolPreview>) { | ||
| 768 | let mut printer = TextPrinter::new(width, style, settings, info, Some(previews)); | ||
| 608 | 769 | ||
| 609 | for child in self.children.iter() { | 770 | for child in self.children.iter() { |
| 610 | child.print(&mut printer, style); | 771 | child.print(&mut printer, style); |
| @@ -737,16 +898,54 @@ fn attrs_to_start(attrs: &[Attribute]) -> Option<usize> { | |||
| 737 | return None; | 898 | return None; |
| 738 | } | 899 | } |
| 739 | 900 | ||
| 740 | fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> { | 901 | fn attrs_to_image(attrs: &[Attribute]) -> Image { |
| 902 | let mut title = None; | ||
| 903 | let mut alt = None; | ||
| 904 | let mut width = None; | ||
| 905 | let mut height = None; | ||
| 906 | let mut src = None; | ||
| 907 | let mut is_emote = false; | ||
| 908 | |||
| 741 | for attr in attrs { | 909 | for attr in attrs { |
| 742 | if attr.name.local.as_ref() != "alt" { | 910 | match attr.name.local.as_ref() { |
| 743 | continue; | 911 | "title" => { |
| 744 | } | 912 | title = Some(attr.value.to_string()); |
| 913 | }, | ||
| 914 | "alt" => { | ||
| 915 | alt = Some(attr.value.to_string()); | ||
| 916 | }, | ||
| 917 | "width" => { | ||
| 918 | if let Ok(val) = u16::from_str(attr.value.as_ref()) { | ||
| 919 | width = Some(val); | ||
| 920 | } | ||
| 921 | }, | ||
| 922 | "height" => { | ||
| 923 | if let Ok(val) = u16::from_str(attr.value.as_ref()) { | ||
| 924 | height = Some(val); | ||
| 925 | } | ||
| 926 | }, | ||
| 927 | "src" => { | ||
| 928 | let uri = OwnedMxcUri::from(attr.value.to_string()); | ||
| 745 | 929 | ||
| 746 | return Some(attr.value.to_string()); | 930 | if uri.is_valid() { |
| 931 | src = Some(uri); | ||
| 932 | } | ||
| 933 | }, | ||
| 934 | "data-mx-emoticon" => { | ||
| 935 | is_emote = true; | ||
| 936 | }, | ||
| 937 | _ => (), | ||
| 938 | } | ||
| 747 | } | 939 | } |
| 748 | 940 | ||
| 749 | return None; | 941 | Image { |
| 942 | title, | ||
| 943 | alt, | ||
| 944 | width, | ||
| 945 | height, | ||
| 946 | is_emote, | ||
| 947 | src: src.map(MediaSource::Plain), | ||
| 948 | } | ||
| 750 | } | 949 | } |
| 751 | 950 | ||
| 752 | fn attrs_to_href(attrs: &[Attribute]) -> Option<String> { | 951 | fn attrs_to_href(attrs: &[Attribute]) -> Option<String> { |
| @@ -945,7 +1144,7 @@ fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren { | |||
| 945 | "hr" => StyleTreeNode::Ruler, | 1144 | "hr" => StyleTreeNode::Ruler, |
| 946 | "br" => StyleTreeNode::Break, | 1145 | "br" => StyleTreeNode::Break, |
| 947 | 1146 | ||
| 948 | "img" => StyleTreeNode::Image(attrs_to_alt(&attrs.borrow())), | 1147 | "img" => StyleTreeNode::Image(attrs_to_image(&attrs.borrow())), |
| 949 | 1148 | ||
| 950 | // These don't render in any special way. | 1149 | // These don't render in any special way. |
| 951 | "details" | "html" | "summary" | "sub" | "sup" => { | 1150 | "details" | "html" | "summary" | "sub" | "sup" => { |
src/message/mod.rs +166 −160
| @@ -33,7 +33,6 @@ use matrix_sdk::ruma::{OwnedTransactionId, UserId}; | |||
| 33 | use matrix_sdk::send_queue::SendHandle; | 33 | use matrix_sdk::send_queue::SendHandle; |
| 34 | use modalkit::editing::cursor::Cursor; | 34 | use modalkit::editing::cursor::Cursor; |
| 35 | use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL}; | 35 | use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL}; |
| 36 | use ratatui_image::sliced::SlicedProtocol; | ||
| 37 | 36 | ||
| 38 | use crate::base::MessageEdits; | 37 | use crate::base::MessageEdits; |
| 39 | use crate::message::html::{StyleTree, parse_matrix_html}; | 38 | use crate::message::html::{StyleTree, parse_matrix_html}; |
| @@ -53,6 +52,7 @@ pub mod poll; | |||
| 53 | pub use self::compose::{text_to_message, text_to_text_message_event_content}; | 52 | pub use self::compose::{text_to_message, text_to_text_message_event_content}; |
| 54 | pub use self::html::TreeGenState; | 53 | pub use self::html::TreeGenState; |
| 55 | 54 | ||
| 55 | /// `proto, x, y` | ||
| 56 | type ProtocolPreview = (Arc<SlicedProtocol>, u16, u16); | 56 | type ProtocolPreview = (Arc<SlicedProtocol>, u16, u16); |
| 57 | 57 | ||
| 58 | /// The key used for uniquely identifying messages within a room and its threads. | 58 | /// The key used for uniquely identifying messages within a room and its threads. |
| @@ -114,6 +114,51 @@ const MIN_MSG_LEN: usize = 30; | |||
| 114 | 114 | ||
| 115 | const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS; | 115 | const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS; |
| 116 | 116 | ||
| 117 | /// Macro rule converting a File / Image / Audio / Video to its text content with the shape: | ||
| 118 | /// `[Attached <type>: <content>[ (<human readable file size>)]]` | ||
| 119 | macro_rules! display_file_name { | ||
| 120 | ( $msgtype:ident, $content:expr ) => {{ | ||
| 121 | format!( | ||
| 122 | "[Attached {}: {}{}]", | ||
| 123 | stringify!($msgtype), | ||
| 124 | $content.filename(), | ||
| 125 | $content | ||
| 126 | .info | ||
| 127 | .as_ref() | ||
| 128 | .map(|info| { | ||
| 129 | info.size | ||
| 130 | .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL))) | ||
| 131 | .unwrap_or_else(String::new) | ||
| 132 | }) | ||
| 133 | .unwrap_or_else(String::new) | ||
| 134 | ) | ||
| 135 | }}; | ||
| 136 | } | ||
| 137 | |||
| 138 | /// Macro rule extraction the text caption of a File / Image / Audio / Video | ||
| 139 | macro_rules! display_file_to_text { | ||
| 140 | ( $msgtype:ident, $content:expr ) => {{ | ||
| 141 | if $content | ||
| 142 | .filename | ||
| 143 | .as_ref() | ||
| 144 | .is_none_or(|filename| *filename == $content.body) | ||
| 145 | { | ||
| 146 | return Cow::Borrowed(""); | ||
| 147 | } | ||
| 148 | $content.body.as_str() | ||
| 149 | }}; | ||
| 150 | } | ||
| 151 | |||
| 152 | fn content_filename(msgtype: &MessageType) -> Option<String> { | ||
| 153 | match msgtype { | ||
| 154 | MessageType::Audio(content) => Some(display_file_name!(Audio, content)), | ||
| 155 | MessageType::File(content) => Some(display_file_name!(File, content)), | ||
| 156 | MessageType::Image(content) => Some(display_file_name!(Image, content)), | ||
| 157 | MessageType::Video(content) => Some(display_file_name!(Video, content)), | ||
| 158 | _ => None, | ||
| 159 | } | ||
| 160 | } | ||
| 161 | |||
| 117 | /// Convert the [u64] hash to [usize] as needed. | 162 | /// Convert the [u64] hash to [usize] as needed. |
| 118 | fn hash_finish_usize(hasher: DefaultHasher) -> Option<usize> { | 163 | fn hash_finish_usize(hasher: DefaultHasher) -> Option<usize> { |
| 119 | if USIZE_TOO_SMALL { | 164 | if USIZE_TOO_SMALL { |
| @@ -131,15 +176,13 @@ fn hash_message_id(id: &MessageId) -> Option<usize> { | |||
| 131 | } | 176 | } |
| 132 | 177 | ||
| 133 | /// Before the image is loaded, already display a placeholder frame of the image size. | 178 | /// Before the image is loaded, already display a placeholder frame of the image size. |
| 134 | fn placeholder_frame( | 179 | fn placeholder_frame(text: Option<&str>, outer_width: usize, image_preview_size: &Size) -> String { |
| 135 | text: Option<&str>, | ||
| 136 | outer_width: usize, | ||
| 137 | image_preview_size: &Size, | ||
| 138 | ) -> Option<String> { | ||
| 139 | let Size { width, height } = image_preview_size; | 180 | let Size { width, height } = image_preview_size; |
| 140 | let width = usize::min(*width as usize, outer_width); | 181 | let width = usize::min(*width as usize, outer_width); |
| 141 | if width < 2 || *height < 2 { | 182 | if width < 2 || *height < 2 { |
| 142 | return None; | 183 | let mut line = "#".repeat(width); |
| 184 | line.push('\n'); | ||
| 185 | return line.repeat(*height as usize); | ||
| 143 | } | 186 | } |
| 144 | let mut placeholder = "\u{230c}".to_string(); | 187 | let mut placeholder = "\u{230c}".to_string(); |
| 145 | placeholder.push_str(&" ".repeat(width - 2)); | 188 | placeholder.push_str(&" ".repeat(width - 2)); |
| @@ -158,7 +201,7 @@ fn placeholder_frame( | |||
| 158 | placeholder.push('\u{230e}'); | 201 | placeholder.push('\u{230e}'); |
| 159 | placeholder.push_str(&" ".repeat(width - 2)); | 202 | placeholder.push_str(&" ".repeat(width - 2)); |
| 160 | placeholder.push_str("\u{230f}\n"); | 203 | placeholder.push_str("\u{230f}\n"); |
| 161 | Some(placeholder) | 204 | placeholder |
| 162 | } | 205 | } |
| 163 | 206 | ||
| 164 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] | 207 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] |
| @@ -398,16 +441,50 @@ fn content_html(msgtype: &MessageType) -> Option<StyleTree> { | |||
| 398 | 441 | ||
| 399 | MessageType::Audio(content) => content.formatted.as_ref(), | 442 | MessageType::Audio(content) => content.formatted.as_ref(), |
| 400 | MessageType::File(content) => content.formatted.as_ref(), | 443 | MessageType::File(content) => content.formatted.as_ref(), |
| 401 | MessageType::Image(content) => content.formatted.as_ref(), | ||
| 402 | MessageType::Video(content) => content.formatted.as_ref(), | 444 | MessageType::Video(content) => content.formatted.as_ref(), |
| 445 | |||
| 446 | MessageType::Image(content) => { | ||
| 447 | let mut html = if let Some(FormattedBody { format: MessageFormat::Html, body }) = | ||
| 448 | &content.formatted | ||
| 449 | { | ||
| 450 | parse_matrix_html(body.as_str()) | ||
| 451 | } else { | ||
| 452 | StyleTree { children: vec![] } | ||
| 453 | }; | ||
| 454 | |||
| 455 | html.children | ||
| 456 | .insert(0, html::StyleTreeNode::Text(display_file_name!(Image, content).into())); | ||
| 457 | |||
| 458 | let src = content.source.clone(); | ||
| 459 | html.children.insert( | ||
| 460 | 0, | ||
| 461 | html::StyleTreeNode::Image(html::Image::new(src, content.info.as_deref())), | ||
| 462 | ); | ||
| 463 | |||
| 464 | return Some(html); | ||
| 465 | }, | ||
| 403 | _ => None, | 466 | _ => None, |
| 404 | }; | 467 | }; |
| 405 | 468 | ||
| 406 | if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted { | 469 | let mut html = if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted { |
| 407 | Some(parse_matrix_html(body.as_str())) | 470 | Some(parse_matrix_html(body.as_str())) |
| 408 | } else { | 471 | } else { |
| 409 | None | 472 | None |
| 473 | }; | ||
| 474 | |||
| 475 | if let Some(filename) = content_filename(msgtype) { | ||
| 476 | let html = html.get_or_insert_with(|| { | ||
| 477 | let text = body_cow_content(msgtype).into_owned(); | ||
| 478 | StyleTree { | ||
| 479 | children: vec![html::StyleTreeNode::Text(text.into())], | ||
| 480 | } | ||
| 481 | }); | ||
| 482 | |||
| 483 | html.children.push(html::StyleTreeNode::Break); | ||
| 484 | html.children.push(html::StyleTreeNode::Text(filename.into())); | ||
| 410 | } | 485 | } |
| 486 | |||
| 487 | html | ||
| 411 | } | 488 | } |
| 412 | 489 | ||
| 413 | #[derive(Clone, Debug)] | 490 | #[derive(Clone, Debug)] |
| @@ -417,7 +494,7 @@ pub enum MessageEvent { | |||
| 417 | Original(Box<OriginalRoomMessageEvent>, MessageEdits), | 494 | Original(Box<OriginalRoomMessageEvent>, MessageEdits), |
| 418 | Redacted(OwnedEventId, Option<String>), | 495 | Redacted(OwnedEventId, Option<String>), |
| 419 | State(Box<AnySyncStateEvent>), | 496 | State(Box<AnySyncStateEvent>), |
| 420 | Sticker(Box<OriginalStickerEvent>, MediaSource), | 497 | Sticker(Box<OriginalStickerEvent>), |
| 421 | Local(OwnedTransactionId, SendHandle, Box<RoomMessageEventContent>), | 498 | Local(OwnedTransactionId, SendHandle, Box<RoomMessageEventContent>), |
| 422 | Poll(Box<Poll>), | 499 | Poll(Box<Poll>), |
| 423 | UnstablePoll(Box<UnstablePoll>), | 500 | UnstablePoll(Box<UnstablePoll>), |
| @@ -489,10 +566,6 @@ impl MessageEvent { | |||
| 489 | self.msgtype().and_then(content_html) | 566 | self.msgtype().and_then(content_html) |
| 490 | } | 567 | } |
| 491 | 568 | ||
| 492 | pub fn filename(&self) -> Option<String> { | ||
| 493 | self.msgtype().and_then(content_filename) | ||
| 494 | } | ||
| 495 | |||
| 496 | pub fn mentions(&self) -> Option<&Mentions> { | 569 | pub fn mentions(&self) -> Option<&Mentions> { |
| 497 | match self { | 570 | match self { |
| 498 | MessageEvent::EncryptedOriginal(..) | | 571 | MessageEvent::EncryptedOriginal(..) | |
| @@ -579,59 +652,6 @@ impl MessageEvent { | |||
| 579 | } | 652 | } |
| 580 | } | 653 | } |
| 581 | 654 | ||
| 582 | /// Macro rule converting a File / Image / Audio / Video to its text content with the shape: | ||
| 583 | /// `[Attached <type>: <content>[ (<human readable file size>)]]` | ||
| 584 | macro_rules! display_file_name { | ||
| 585 | ( $msgtype:ident, $content:expr ) => {{ | ||
| 586 | Some(format!( | ||
| 587 | "[Attached {}: {}{}]", | ||
| 588 | stringify!($msgtype), | ||
| 589 | $content.filename(), | ||
| 590 | $content | ||
| 591 | .info | ||
| 592 | .as_ref() | ||
| 593 | .map(|info| { | ||
| 594 | info.size | ||
| 595 | .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL))) | ||
| 596 | .unwrap_or_else(String::new) | ||
| 597 | }) | ||
| 598 | .unwrap_or_else(String::new) | ||
| 599 | )) | ||
| 600 | }}; | ||
| 601 | } | ||
| 602 | |||
| 603 | /// Macro rule extraction the text caption of a File / Image / Audio / Video | ||
| 604 | macro_rules! display_file_to_text { | ||
| 605 | ( $msgtype:ident, $content:expr ) => {{ | ||
| 606 | if $content | ||
| 607 | .filename | ||
| 608 | .as_ref() | ||
| 609 | .is_none_or(|filename| *filename == $content.body) | ||
| 610 | { | ||
| 611 | return Cow::Borrowed(""); | ||
| 612 | } | ||
| 613 | $content.body.as_str() | ||
| 614 | }}; | ||
| 615 | } | ||
| 616 | |||
| 617 | fn content_filename(msgtype: &MessageType) -> Option<String> { | ||
| 618 | match msgtype { | ||
| 619 | MessageType::Audio(content) => { | ||
| 620 | display_file_name!(Audio, content) | ||
| 621 | }, | ||
| 622 | MessageType::File(content) => { | ||
| 623 | display_file_name!(File, content) | ||
| 624 | }, | ||
| 625 | MessageType::Image(content) => { | ||
| 626 | display_file_name!(Image, content) | ||
| 627 | }, | ||
| 628 | MessageType::Video(content) => { | ||
| 629 | display_file_name!(Video, content) | ||
| 630 | }, | ||
| 631 | _ => None, | ||
| 632 | } | ||
| 633 | } | ||
| 634 | |||
| 635 | fn body_cow_content(msgtype: &MessageType) -> Cow<'_, str> { | 655 | fn body_cow_content(msgtype: &MessageType) -> Cow<'_, str> { |
| 636 | let s = match msgtype { | 656 | let s = match msgtype { |
| 637 | MessageType::Text(content) => content.body.as_str(), | 657 | MessageType::Text(content) => content.body.as_str(), |
| @@ -865,7 +885,7 @@ impl<'a> MessageFormatter<'a> { | |||
| 865 | info: &'a RoomInfo, | 885 | info: &'a RoomInfo, |
| 866 | settings: &'a ApplicationSettings, | 886 | settings: &'a ApplicationSettings, |
| 867 | previews: &'a PreviewManager, | 887 | previews: &'a PreviewManager, |
| 868 | ) -> Option<ProtocolPreview> { | 888 | ) -> Vec<ProtocolPreview> { |
| 869 | let reply_style = if settings.tunables.message_user_color { | 889 | let reply_style = if settings.tunables.message_user_color { |
| 870 | style.patch(settings.get_user_color(&msg.sender)) | 890 | style.patch(settings.get_user_color(&msg.sender)) |
| 871 | } else { | 891 | } else { |
| @@ -894,12 +914,15 @@ impl<'a> MessageFormatter<'a> { | |||
| 894 | ); | 914 | ); |
| 895 | 915 | ||
| 896 | // Determine the image offset of the reply header, taking into account the formatting | 916 | // Determine the image offset of the reply header, taking into account the formatting |
| 897 | let proto = proto.map(|p| { | 917 | let proto = proto |
| 898 | let y_off = text.lines.len() as u16; | 918 | .into_iter() |
| 899 | // Adjust x_off by 2 to account for the vertical line and indent | 919 | .map(|(p, x, y)| { |
| 900 | let x_off = self.cols.user_gutter_width(settings) + 2; | 920 | let y_off = text.lines.len() as u16; |
| 901 | (p, x_off, y_off) | 921 | // Adjust x_off by 2 to account for the vertical line and indent |
| 902 | }); | 922 | let x_off = self.cols.user_gutter_width(settings) + 2; |
| 923 | (p, x + x_off, y + y_off) | ||
| 924 | }) | ||
| 925 | .collect(); | ||
| 903 | 926 | ||
| 904 | for line in replied.lines.iter_mut() { | 927 | for line in replied.lines.iter_mut() { |
| 905 | line.spans.insert(0, Span::styled(THICK_VERTICAL, style)); | 928 | line.spans.insert(0, Span::styled(THICK_VERTICAL, style)); |
| @@ -919,25 +942,28 @@ impl<'a> MessageFormatter<'a> { | |||
| 919 | settings: &ApplicationSettings, | 942 | settings: &ApplicationSettings, |
| 920 | previews: &'a PreviewManager, | 943 | previews: &'a PreviewManager, |
| 921 | ) -> Vec<ProtocolPreview> { | 944 | ) -> Vec<ProtocolPreview> { |
| 922 | let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings, self.info); | 945 | let mut emojis = printer::TextPrinter::new( |
| 946 | self.width(), | ||
| 947 | style, | ||
| 948 | self.settings, | ||
| 949 | self.info, | ||
| 950 | Some(previews), | ||
| 951 | ); | ||
| 923 | let mut reactions = 0; | 952 | let mut reactions = 0; |
| 924 | let mut protos = Vec::new(); | ||
| 925 | 953 | ||
| 926 | for (key, count, source) in counts { | 954 | for (key, count, source) in counts { |
| 927 | if reactions != 0 { | 955 | if reactions != 0 { |
| 928 | emojis.push_str(" ", style); | 956 | emojis.push_str(" ", style); |
| 929 | } | 957 | } |
| 930 | 958 | ||
| 931 | let proto = match source | 959 | let proto = |
| 932 | .as_ref() | 960 | match source.as_ref().and_then(|source| previews.get(source, PreviewKind::Emoji)) { |
| 933 | .and_then(|source| previews.get(source, PreviewKind::Reaction)) | 961 | Some(ImageStatus::Loaded(backend)) => Some(Some(backend)), |
| 934 | { | 962 | // Use empty space as placeholder |
| 935 | Some(ImageStatus::Loaded(backend)) => Some(Some(backend)), | 963 | Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None), |
| 936 | // Use empty space as placeholder | 964 | // Fall back to text |
| 937 | Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None), | 965 | None | Some(ImageStatus::Error(_)) => None, |
| 938 | // Fall back to text | 966 | }; |
| 939 | None | Some(ImageStatus::Error(_)) => None, | ||
| 940 | }; | ||
| 941 | 967 | ||
| 942 | let name = if proto.is_some() { | 968 | let name = if proto.is_some() { |
| 943 | " " | 969 | " " |
| @@ -961,15 +987,10 @@ impl<'a> MessageFormatter<'a> { | |||
| 961 | 987 | ||
| 962 | emojis.push_str("[", style); | 988 | emojis.push_str("[", style); |
| 963 | if let Some(Some(proto)) = proto { | 989 | if let Some(Some(proto)) = proto { |
| 964 | let proto = Arc::clone(proto); | 990 | emojis.push_emoji(proto, style); |
| 965 | 991 | } else { | |
| 966 | let (x, y) = emojis.cursor_pos(); | 992 | emojis.push_str(name, style); |
| 967 | let y = (y + text.lines.len()) as u16; | ||
| 968 | let x = x as u16 + self.cols.user_gutter_width(settings); | ||
| 969 | |||
| 970 | protos.push((proto, x, y)); | ||
| 971 | } | 993 | } |
| 972 | emojis.push_str(name, style); | ||
| 973 | emojis.push_str(" ", style); | 994 | emojis.push_str(" ", style); |
| 974 | emojis.push_span_nobreak(Span::styled(count.len().to_string(), style)); | 995 | emojis.push_span_nobreak(Span::styled(count.len().to_string(), style)); |
| 975 | emojis.push_str("]", style); | 996 | emojis.push_str("]", style); |
| @@ -978,10 +999,17 @@ impl<'a> MessageFormatter<'a> { | |||
| 978 | } | 999 | } |
| 979 | 1000 | ||
| 980 | if reactions > 0 { | 1001 | if reactions > 0 { |
| 981 | self.push_text(emojis.finish(), style, text); | 1002 | let (txt, protos) = emojis.finish(); |
| 982 | } | 1003 | |
| 1004 | let x_off = self.cols.user_gutter_width(settings); | ||
| 1005 | let y_off = text.lines.len() as u16; | ||
| 983 | 1006 | ||
| 984 | protos | 1007 | self.push_text(txt, style, text); |
| 1008 | |||
| 1009 | protos.into_iter().map(|(p, x, y)| (p, x + x_off, y + y_off)).collect() | ||
| 1010 | } else { | ||
| 1011 | vec![] | ||
| 1012 | } | ||
| 985 | } | 1013 | } |
| 986 | 1014 | ||
| 987 | fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>, style: Style) { | 1015 | fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>, style: Style) { |
| @@ -992,7 +1020,8 @@ impl<'a> MessageFormatter<'a> { | |||
| 992 | // If we have threaded replies to this message, show how many. | 1020 | // If we have threaded replies to this message, show how many. |
| 993 | let plural = len != 1; | 1021 | let plural = len != 1; |
| 994 | let mut threaded = | 1022 | let mut threaded = |
| 995 | printer::TextPrinter::new(self.width(), style, self.settings, self.info).literal(true); | 1023 | printer::TextPrinter::new(self.width(), style, self.settings, self.info, None) |
| 1024 | .literal(true); | ||
| 996 | let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD)); | 1025 | let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD)); |
| 997 | threaded.push_str(" \u{2937} ", style); | 1026 | threaded.push_str(" \u{2937} ", style); |
| 998 | threaded.push_span_nobreak(len); | 1027 | threaded.push_span_nobreak(len); |
| @@ -1002,7 +1031,7 @@ impl<'a> MessageFormatter<'a> { | |||
| 1002 | threaded.push_str(" reply in thread", style); | 1031 | threaded.push_str(" reply in thread", style); |
| 1003 | } | 1032 | } |
| 1004 | 1033 | ||
| 1005 | self.push_text(threaded.finish(), style, text); | 1034 | self.push_text(threaded.finish().0, style, text); |
| 1006 | } | 1035 | } |
| 1007 | } | 1036 | } |
| 1008 | 1037 | ||
| @@ -1010,7 +1039,6 @@ pub struct Message { | |||
| 1010 | pub event: MessageEvent, | 1039 | pub event: MessageEvent, |
| 1011 | pub sender: OwnedUserId, | 1040 | pub sender: OwnedUserId, |
| 1012 | pub timestamp: MessageTimeStamp, | 1041 | pub timestamp: MessageTimeStamp, |
| 1013 | pub downloaded: bool, | ||
| 1014 | pub html: Option<StyleTree>, | 1042 | pub html: Option<StyleTree>, |
| 1015 | } | 1043 | } |
| 1016 | 1044 | ||
| @@ -1029,9 +1057,8 @@ fn is_after_read_marker(prev: Option<&Message>, marker: Option<&OwnedEventId>) - | |||
| 1029 | impl Message { | 1057 | impl Message { |
| 1030 | pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self { | 1058 | pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self { |
| 1031 | let html = event.html(); | 1059 | let html = event.html(); |
| 1032 | let downloaded = false; | ||
| 1033 | 1060 | ||
| 1034 | Message { event, sender, timestamp, downloaded, html } | 1061 | Message { event, sender, timestamp, html } |
| 1035 | } | 1062 | } |
| 1036 | 1063 | ||
| 1037 | pub fn reply_to(&self) -> Option<OwnedEventId> { | 1064 | pub fn reply_to(&self) -> Option<OwnedEventId> { |
| @@ -1093,15 +1120,11 @@ impl Message { | |||
| 1093 | } | 1120 | } |
| 1094 | } | 1121 | } |
| 1095 | 1122 | ||
| 1096 | pub fn image_preview(&self) -> Option<&MediaSource> { | 1123 | pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> { |
| 1097 | if let Some(MessageType::Image(c)) = self.event.msgtype() { | 1124 | if let Some(html) = &self.html { |
| 1098 | return Some(&c.source); | 1125 | html.image_previews() |
| 1099 | } | 1126 | } else { |
| 1100 | 1127 | vec![] | |
| 1101 | match &self.event { | ||
| 1102 | MessageEvent::Sticker(_, source) => Some(source), | ||
| 1103 | |||
| 1104 | _ => None, | ||
| 1105 | } | 1128 | } |
| 1106 | } | 1129 | } |
| 1107 | 1130 | ||
| @@ -1315,10 +1338,7 @@ impl Message { | |||
| 1315 | if let Some(r) = reply { | 1338 | if let Some(r) = reply { |
| 1316 | if let Some(r) = r { | 1339 | if let Some(r) = r { |
| 1317 | // Format the reply header, push it into the `Text` buffer, and get any image. | 1340 | // Format the reply header, push it into the `Text` buffer, and get any image. |
| 1318 | let proto_reply = fmt.push_in_reply(r, style, &mut text, info, settings, previews); | 1341 | protos = fmt.push_in_reply(r, style, &mut text, info, settings, previews); |
| 1319 | if let Some(proto) = proto_reply { | ||
| 1320 | protos.push(proto) | ||
| 1321 | } | ||
| 1322 | } else { | 1342 | } else { |
| 1323 | fmt.push_spans( | 1343 | fmt.push_spans( |
| 1324 | Line::from(vec![ | 1344 | Line::from(vec![ |
| @@ -1337,13 +1357,16 @@ impl Message { | |||
| 1337 | let (msg, proto) = self.show_msg(width, style, settings, previews, info); | 1357 | let (msg, proto) = self.show_msg(width, style, settings, previews, info); |
| 1338 | 1358 | ||
| 1339 | // Given our text so far, determine the image offset. | 1359 | // Given our text so far, determine the image offset. |
| 1340 | if let Some(p) = proto { | 1360 | { |
| 1341 | let y_off = text.lines.len() as u16; | 1361 | let y_off = text.lines.len() as u16; |
| 1342 | let x_off = fmt.cols.user_gutter_width(settings); | 1362 | let x_off = fmt.cols.user_gutter_width(settings); |
| 1343 | 1363 | ||
| 1344 | // Account for extra lines printed before the message; | 1364 | // Account for extra lines printed before the message; |
| 1345 | let y_off = y_off + fmt.message_start_line(); | 1365 | let y_off = y_off + fmt.message_start_line(); |
| 1346 | protos.push((p, x_off, y_off)); | 1366 | |
| 1367 | for (p, x, y) in proto { | ||
| 1368 | protos.push((p, x + x_off, y + y_off)); | ||
| 1369 | } | ||
| 1347 | } | 1370 | } |
| 1348 | 1371 | ||
| 1349 | fmt.push_text(msg, style, &mut text); | 1372 | fmt.push_text(msg, style, &mut text); |
| @@ -1405,44 +1428,16 @@ impl Message { | |||
| 1405 | settings: &'a ApplicationSettings, | 1428 | settings: &'a ApplicationSettings, |
| 1406 | previews: &'a PreviewManager, | 1429 | previews: &'a PreviewManager, |
| 1407 | info: &'a RoomInfo, | 1430 | info: &'a RoomInfo, |
| 1408 | ) -> (Text<'a>, Option<Arc<SlicedProtocol>>) { | 1431 | ) -> (Text<'a>, Vec<ProtocolPreview>) { |
| 1409 | let mut proto = None; | 1432 | let mut protos = vec![]; |
| 1410 | let placeholder = match self | ||
| 1411 | .image_preview() | ||
| 1412 | .and_then(|source| previews.get(source, PreviewKind::Message)) | ||
| 1413 | { | ||
| 1414 | None => None, | ||
| 1415 | Some(ImageStatus::Queued(image_preview_size)) => { | ||
| 1416 | placeholder_frame(Some("Queued..."), width, image_preview_size) | ||
| 1417 | }, | ||
| 1418 | Some(ImageStatus::Downloading(image_preview_size)) => { | ||
| 1419 | placeholder_frame(Some("Downloading..."), width, image_preview_size) | ||
| 1420 | }, | ||
| 1421 | Some(ImageStatus::Loaded(backend)) => { | ||
| 1422 | proto = Some(Arc::clone(backend)); | ||
| 1423 | placeholder_frame(None, width, &backend.size()) | ||
| 1424 | }, | ||
| 1425 | Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")), | ||
| 1426 | }; | ||
| 1427 | |||
| 1428 | let mut text = if let Some(placeholder) = placeholder { | ||
| 1429 | wrapped_text(placeholder, width, style) | ||
| 1430 | } else { | ||
| 1431 | Default::default() | ||
| 1432 | }; | ||
| 1433 | |||
| 1434 | if let Some(mut filename) = self.event.filename() { | ||
| 1435 | if self.downloaded { | ||
| 1436 | filename.push_str(" \u{2705}"); | ||
| 1437 | } | ||
| 1438 | |||
| 1439 | text += wrapped_text(filename, width, style); | ||
| 1440 | } | ||
| 1441 | 1433 | ||
| 1434 | let mut text = Default::default(); | ||
| 1442 | if let Some(html) = &self.html && | 1435 | if let Some(html) = &self.html && |
| 1443 | settings.tunables.message_formatted_display | 1436 | settings.tunables.message_formatted_display |
| 1444 | { | 1437 | { |
| 1445 | text += html.to_text(width, style, settings, info); | 1438 | let (t, p) = html.render(width, style, settings, info, previews); |
| 1439 | text += t; | ||
| 1440 | protos = p; | ||
| 1446 | } else { | 1441 | } else { |
| 1447 | let mut msg = self.event.body(); | 1442 | let mut msg = self.event.body(); |
| 1448 | if settings.tunables.message_shortcode_display { | 1443 | if settings.tunables.message_shortcode_display { |
| @@ -1451,7 +1446,7 @@ impl Message { | |||
| 1451 | text += wrapped_text(msg, width, style); | 1446 | text += wrapped_text(msg, width, style); |
| 1452 | }; | 1447 | }; |
| 1453 | 1448 | ||
| 1454 | (text, proto) | 1449 | (text, protos) |
| 1455 | } | 1450 | } |
| 1456 | 1451 | ||
| 1457 | fn sender_span<'a>( | 1452 | fn sender_span<'a>( |
| @@ -1502,7 +1497,6 @@ impl Message { | |||
| 1502 | pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) { | 1497 | pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) { |
| 1503 | self.event.redact(redaction); | 1498 | self.event.redact(redaction); |
| 1504 | self.html = None; | 1499 | self.html = None; |
| 1505 | self.downloaded = false; | ||
| 1506 | } | 1500 | } |
| 1507 | 1501 | ||
| 1508 | pub fn set_edits(&mut self, new_edits: MessageEdits) { | 1502 | pub fn set_edits(&mut self, new_edits: MessageEdits) { |
| @@ -1656,9 +1650,21 @@ impl From<OriginalStickerEvent> for Message { | |||
| 1656 | let timestamp = event.origin_server_ts.into(); | 1650 | let timestamp = event.origin_server_ts.into(); |
| 1657 | let user_id = event.sender.clone(); | 1651 | let user_id = event.sender.clone(); |
| 1658 | let source = event.content.source.clone().into(); | 1652 | let source = event.content.source.clone().into(); |
| 1659 | let content = MessageEvent::Sticker(event.into(), source); | ||
| 1660 | 1653 | ||
| 1661 | Message::new(content, user_id, timestamp) | 1654 | let html_image = |
| 1655 | html::StyleTreeNode::Image(html::Image::new(source, Some(&event.content.info))); | ||
| 1656 | |||
| 1657 | let content = MessageEvent::Sticker(event.into()); | ||
| 1658 | let mut msg = Message::new(content, user_id, timestamp); | ||
| 1659 | |||
| 1660 | msg.html = Some(StyleTree { | ||
| 1661 | children: vec![ | ||
| 1662 | html::StyleTreeNode::Text("* sent a sticker:".into()), | ||
| 1663 | html_image, | ||
| 1664 | ], | ||
| 1665 | }); | ||
| 1666 | |||
| 1667 | msg | ||
| 1662 | } | 1668 | } |
| 1663 | } | 1669 | } |
| 1664 | 1670 | ||
| @@ -1850,8 +1856,8 @@ pub mod tests { | |||
| 1850 | 1856 | ||
| 1851 | #[test] | 1857 | #[test] |
| 1852 | fn test_placeholder_frame() { | 1858 | fn test_placeholder_frame() { |
| 1853 | fn pretty_frame_test(str: &str) -> Option<String> { | 1859 | fn pretty_frame_test(str: &str) -> String { |
| 1854 | Some(str[1..].to_string()) | 1860 | str[1..].to_string() |
| 1855 | } | 1861 | } |
| 1856 | 1862 | ||
| 1857 | assert_eq!( | 1863 | assert_eq!( |
| @@ -1877,9 +1883,9 @@ pub mod tests { | |||
| 1877 | "# | 1883 | "# |
| 1878 | ) | 1884 | ) |
| 1879 | ); | 1885 | ); |
| 1880 | assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), None); | 1886 | assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), "#\n#\n#\n#\n"); |
| 1881 | 1887 | ||
| 1882 | assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), None); | 1888 | assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), "####\n"); |
| 1883 | 1889 | ||
| 1884 | assert_eq!( | 1890 | assert_eq!( |
| 1885 | placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }), | 1891 | placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }), |
src/message/printer.rs +33 −10
| @@ -5,6 +5,7 @@ | |||
| 5 | //! contents). | 5 | //! contents). |
| 6 | 6 | ||
| 7 | use crate::base::RoomInfo; | 7 | use crate::base::RoomInfo; |
| 8 | use crate::message::ProtocolPreview; | ||
| 8 | use crate::prelude::*; | 9 | use crate::prelude::*; |
| 9 | use crate::util::{ | 10 | use crate::util::{ |
| 10 | replace_emojis_in_line, | 11 | replace_emojis_in_line, |
| @@ -18,6 +19,7 @@ use crate::util::{ | |||
| 18 | /// Wrap styled text for the current terminal width. | 19 | /// Wrap styled text for the current terminal width. |
| 19 | pub struct TextPrinter<'a> { | 20 | pub struct TextPrinter<'a> { |
| 20 | text: Text<'a>, | 21 | text: Text<'a>, |
| 22 | images: Vec<ProtocolPreview>, | ||
| 21 | width: usize, | 23 | width: usize, |
| 22 | base_style: Style, | 24 | base_style: Style, |
| 23 | 25 | ||
| @@ -28,6 +30,7 @@ pub struct TextPrinter<'a> { | |||
| 28 | 30 | ||
| 29 | pub(super) settings: &'a ApplicationSettings, | 31 | pub(super) settings: &'a ApplicationSettings, |
| 30 | pub(super) info: &'a RoomInfo, | 32 | pub(super) info: &'a RoomInfo, |
| 33 | pub(super) previews: Option<&'a PreviewManager>, | ||
| 31 | } | 34 | } |
| 32 | 35 | ||
| 33 | impl<'a> TextPrinter<'a> { | 36 | impl<'a> TextPrinter<'a> { |
| @@ -37,9 +40,11 @@ impl<'a> TextPrinter<'a> { | |||
| 37 | base_style: Style, | 40 | base_style: Style, |
| 38 | settings: &'a ApplicationSettings, | 41 | settings: &'a ApplicationSettings, |
| 39 | info: &'a RoomInfo, | 42 | info: &'a RoomInfo, |
| 43 | previews: Option<&'a PreviewManager>, | ||
| 40 | ) -> Self { | 44 | ) -> Self { |
| 41 | TextPrinter { | 45 | TextPrinter { |
| 42 | text: Text::default(), | 46 | text: Text::default(), |
| 47 | images: vec![], | ||
| 43 | width, | 48 | width, |
| 44 | base_style, | 49 | base_style, |
| 45 | 50 | ||
| @@ -49,14 +54,10 @@ impl<'a> TextPrinter<'a> { | |||
| 49 | literal: false, | 54 | literal: false, |
| 50 | settings, | 55 | settings, |
| 51 | info, | 56 | info, |
| 57 | previews, | ||
| 52 | } | 58 | } |
| 53 | } | 59 | } |
| 54 | 60 | ||
| 55 | /// The `(x, y)` position where the next text will be printed. | ||
| 56 | pub fn cursor_pos(&self) -> (usize, usize) { | ||
| 57 | (self.curr_width, self.text.lines.len()) | ||
| 58 | } | ||
| 59 | |||
| 60 | /// Configure the alignment for each line. | 61 | /// Configure the alignment for each line. |
| 61 | pub fn align(mut self, alignment: Alignment) -> Self { | 62 | pub fn align(mut self, alignment: Alignment) -> Self { |
| 62 | self.alignment = alignment; | 63 | self.alignment = alignment; |
| @@ -96,6 +97,7 @@ impl<'a> TextPrinter<'a> { | |||
| 96 | pub fn sub(&self, indent: usize) -> Self { | 97 | pub fn sub(&self, indent: usize) -> Self { |
| 97 | TextPrinter { | 98 | TextPrinter { |
| 98 | text: Text::default(), | 99 | text: Text::default(), |
| 100 | images: vec![], | ||
| 99 | width: self.width.saturating_sub(indent), | 101 | width: self.width.saturating_sub(indent), |
| 100 | base_style: self.base_style, | 102 | base_style: self.base_style, |
| 101 | 103 | ||
| @@ -105,6 +107,7 @@ impl<'a> TextPrinter<'a> { | |||
| 105 | literal: self.literal, | 107 | literal: self.literal, |
| 106 | settings: self.settings, | 108 | settings: self.settings, |
| 107 | info: self.info, | 109 | info: self.info, |
| 110 | previews: self.previews, | ||
| 108 | } | 111 | } |
| 109 | } | 112 | } |
| 110 | 113 | ||
| @@ -306,10 +309,29 @@ impl<'a> TextPrinter<'a> { | |||
| 306 | self.text.lines.extend(text.lines); | 309 | self.text.lines.extend(text.lines); |
| 307 | } | 310 | } |
| 308 | 311 | ||
| 312 | /// Push an image that will be forced into an Emoji size (1 row, 2 columns). | ||
| 313 | pub fn push_emoji(&mut self, image: &Arc<SlicedProtocol>, style: Style) { | ||
| 314 | if self.curr_width + 2 > self.width { | ||
| 315 | self.commit(); | ||
| 316 | } | ||
| 317 | |||
| 318 | self.push_image(image); | ||
| 319 | self.curr_spans.push(Span::styled(" ", style)); | ||
| 320 | self.curr_width += 2; | ||
| 321 | } | ||
| 322 | |||
| 323 | /// Push an image without placeholder | ||
| 324 | pub fn push_image(&mut self, image: &Arc<SlicedProtocol>) { | ||
| 325 | let y = self.text.lines.len() as u16; | ||
| 326 | let x = self.curr_width as u16; | ||
| 327 | |||
| 328 | self.images.push((Arc::clone(image), x, y)); | ||
| 329 | } | ||
| 330 | |||
| 309 | /// Render the contents of this printer as [Text]. | 331 | /// Render the contents of this printer as [Text]. |
| 310 | pub fn finish(mut self) -> Text<'a> { | 332 | pub fn finish(mut self) -> (Text<'a>, Vec<ProtocolPreview>) { |
| 311 | self.commit(); | 333 | self.commit(); |
| 312 | self.text | 334 | (self.text, self.images) |
| 313 | } | 335 | } |
| 314 | } | 336 | } |
| 315 | 337 | ||
| @@ -323,9 +345,9 @@ pub mod tests { | |||
| 323 | fn test_push_nobreak() { | 345 | fn test_push_nobreak() { |
| 324 | let settings = mock_settings(); | 346 | let settings = mock_settings(); |
| 325 | let info = mock_room(); | 347 | let info = mock_room(); |
| 326 | let mut printer = TextPrinter::new(5, Style::default(), &settings, &info); | 348 | let mut printer = TextPrinter::new(5, Style::default(), &settings, &info, None); |
| 327 | printer.push_span_nobreak("hello world".into()); | 349 | printer.push_span_nobreak("hello world".into()); |
| 328 | let text = printer.finish(); | 350 | let text = printer.finish().0; |
| 329 | assert_eq!(text.lines.len(), 1); | 351 | assert_eq!(text.lines.len(), 1); |
| 330 | assert_eq!(text.lines[0].spans.len(), 1); | 352 | assert_eq!(text.lines[0].spans.len(), 1); |
| 331 | assert_eq!(text.lines[0].spans[0].content, "hello world"); | 353 | assert_eq!(text.lines[0].spans[0].content, "hello world"); |
| @@ -335,10 +357,11 @@ pub mod tests { | |||
| 335 | fn test_push_str_wide_char_wider_than_width() { | 357 | fn test_push_str_wide_char_wider_than_width() { |
| 336 | let settings = mock_settings(); | 358 | let settings = mock_settings(); |
| 337 | let info = mock_room(); | 359 | let info = mock_room(); |
| 338 | let mut printer = TextPrinter::new(1, Style::default(), &settings, &info); | 360 | let mut printer = TextPrinter::new(1, Style::default(), &settings, &info, None); |
| 339 | printer.push_str("a世b", Style::default()); | 361 | printer.push_str("a世b", Style::default()); |
| 340 | let text = printer.finish(); | 362 | let text = printer.finish(); |
| 341 | let lines: Vec<String> = text | 363 | let lines: Vec<String> = text |
| 364 | .0 | ||
| 342 | .lines | 365 | .lines |
| 343 | .iter() | 366 | .iter() |
| 344 | .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect()) | 367 | .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect()) |
src/prelude.rs +1
| @@ -68,6 +68,7 @@ pub use ratatui::layout::{Alignment, Rect, Size}; | |||
| 68 | pub use ratatui::style::{Color, Modifier as StyleModifier, Style}; | 68 | pub use ratatui::style::{Color, Modifier as StyleModifier, Style}; |
| 69 | pub use ratatui::text::{Line, Span, Text}; | 69 | pub use ratatui::text::{Line, Span, Text}; |
| 70 | pub use ratatui::widgets::{Paragraph, StatefulWidget, Widget}; | 70 | pub use ratatui::widgets::{Paragraph, StatefulWidget, Widget}; |
| 71 | pub use ratatui_image::sliced::SlicedProtocol; | ||
| 71 | pub use unicode_segmentation::UnicodeSegmentation; | 72 | pub use unicode_segmentation::UnicodeSegmentation; |
| 72 | pub use unicode_width::UnicodeWidthStr; | 73 | pub use unicode_width::UnicodeWidthStr; |
| 73 | pub use url::Url; | 74 | pub use url::Url; |
src/preview.rs +37 −7
| @@ -1,7 +1,6 @@ | |||
| 1 | use matrix_sdk::Media; | 1 | use matrix_sdk::Media; |
| 2 | use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey}; | 2 | use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey}; |
| 3 | use ratatui_image::picker::Picker; | 3 | use ratatui_image::picker::Picker; |
| 4 | use ratatui_image::sliced::SlicedProtocol; | ||
| 5 | use ratatui_image::{FilterType, Resize}; | 4 | use ratatui_image::{FilterType, Resize}; |
| 6 | use tokio::sync::Semaphore; | 5 | use tokio::sync::Semaphore; |
| 7 | 6 | ||
| @@ -17,15 +16,46 @@ pub enum ImageStatus { | |||
| 17 | 16 | ||
| 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | 17 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 19 | pub enum PreviewKind { | 18 | pub enum PreviewKind { |
| 20 | Message, | 19 | /// A custom `width, height` is given in pixels or defaults to the config |
| 21 | Reaction, | 20 | Custom(Option<u16>, Option<u16>), |
| 21 | |||
| 22 | /// Force the image to be rendered in Emoji presentation (i.e., 1x2 characters) | ||
| 23 | /// | ||
| 24 | /// This is used primarily for custom message reactions and for the `data-mx-emoticon` | ||
| 25 | /// attribute on images, which is typically used when forcing stickers to appear like | ||
| 26 | /// custom Emoji. | ||
| 27 | /// | ||
| 28 | /// In the future, we could potentially investigate using this as a way to also handle | ||
| 29 | /// troublesome ZWJ combinations that confuse terminals or ratatui by not having clear | ||
| 30 | /// widths across implementations. | ||
| 31 | Emoji, | ||
| 32 | } | ||
| 33 | |||
| 34 | impl Default for PreviewKind { | ||
| 35 | fn default() -> Self { | ||
| 36 | Self::Custom(None, None) | ||
| 37 | } | ||
| 22 | } | 38 | } |
| 23 | 39 | ||
| 24 | impl PreviewKind { | 40 | impl PreviewKind { |
| 25 | fn image_size(self, image_preview: &ImagePreviewValues) -> Size { | 41 | fn image_size(self, picker: &Picker, image_preview: &ImagePreviewValues) -> Size { |
| 26 | match self { | 42 | match self { |
| 27 | Self::Message => image_preview.size, | 43 | Self::Emoji => Size { width: 2, height: 1 }, |
| 28 | Self::Reaction => Size { width: 2, height: 1 }, | 44 | Self::Custom(width, height) => { |
| 45 | let font_size = picker.font_size(); | ||
| 46 | |||
| 47 | let width = width | ||
| 48 | .map(|width| width.div_ceil(font_size.width)) | ||
| 49 | .unwrap_or(image_preview.size.width) | ||
| 50 | .min(image_preview.size.width); | ||
| 51 | |||
| 52 | let height = height | ||
| 53 | .map(|height| height.div_ceil(font_size.height)) | ||
| 54 | .unwrap_or(image_preview.size.height) | ||
| 55 | .min(image_preview.size.height); | ||
| 56 | |||
| 57 | Size { width, height } | ||
| 58 | }, | ||
| 29 | } | 59 | } |
| 30 | } | 60 | } |
| 31 | } | 61 | } |
| @@ -91,7 +121,7 @@ impl PreviewManager { | |||
| 91 | return; | 121 | return; |
| 92 | } | 122 | } |
| 93 | 123 | ||
| 94 | let size = kind.image_size(&settings.tunables.image_preview); | 124 | let size = kind.image_size(&self.picker, &settings.tunables.image_preview); |
| 95 | self.previews.insert(key, ImageStatus::Queued(size)); | 125 | self.previews.insert(key, ImageStatus::Queued(size)); |
| 96 | } | 126 | } |
| 97 | } | 127 | } |
src/windows/room/chat.rs +2 −4
| @@ -197,7 +197,7 @@ impl ChatState { | |||
| 197 | let settings = &store.application.settings; | 197 | let settings = &store.application.settings; |
| 198 | let info = store.application.rooms.get_or_default(self.room_id.clone()); | 198 | let info = store.application.rooms.get_or_default(self.room_id.clone()); |
| 199 | 199 | ||
| 200 | let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?; | 200 | let msg = self.scrollback.get(info).ok_or(IambError::NoSelectedMessage)?; |
| 201 | 201 | ||
| 202 | match act { | 202 | match act { |
| 203 | MessageAction::Cancel(skip_confirm) => { | 203 | MessageAction::Cancel(skip_confirm) => { |
| @@ -652,7 +652,7 @@ fn open_links(msg: &Message) -> UIError<IambInfo> { | |||
| 652 | pub async fn msg_download( | 652 | pub async fn msg_download( |
| 653 | ctx: ProgramContext, | 653 | ctx: ProgramContext, |
| 654 | client: &Client, | 654 | client: &Client, |
| 655 | msg: &mut Message, | 655 | msg: &Message, |
| 656 | settings: &ApplicationSettings, | 656 | settings: &ApplicationSettings, |
| 657 | filename: Option<PathBuf>, | 657 | filename: Option<PathBuf>, |
| 658 | flags: DownloadFlags, | 658 | flags: DownloadFlags, |
| @@ -732,8 +732,6 @@ pub async fn msg_download( | |||
| 732 | let bytes = media.get_media_content(&req, true).await.map_err(IambError::from)?; | 732 | let bytes = media.get_media_content(&req, true).await.map_err(IambError::from)?; |
| 733 | 733 | ||
| 734 | fs::write(filename.as_path(), bytes.as_slice())?; | 734 | fs::write(filename.as_path(), bytes.as_slice())?; |
| 735 | |||
| 736 | msg.downloaded = true; | ||
| 737 | } else if !flags.contains(DownloadFlags::OPEN) { | 735 | } else if !flags.contains(DownloadFlags::OPEN) { |
| 738 | let msg = format!( | 736 | let msg = format!( |
| 739 | "The file {} already exists; add ! to end of command to overwrite it.", | 737 | "The file {} already exists; add ! to end of command to overwrite it.", |
src/windows/room/message.rs +8 −10
| @@ -81,7 +81,6 @@ impl MessageState { | |||
| 81 | 81 | ||
| 82 | match act { | 82 | match act { |
| 83 | MessageAction::Download(filename, flags) => { | 83 | MessageAction::Download(filename, flags) => { |
| 84 | let msg = info.get_message_mut(&self.id()).unwrap(); | ||
| 85 | chat::msg_download( | 84 | chat::msg_download( |
| 86 | ctx, | 85 | ctx, |
| 87 | &store.application.worker.client, | 86 | &store.application.worker.client, |
| @@ -262,16 +261,15 @@ impl StatefulWidget for MessageWidget<'_> { | |||
| 262 | 261 | ||
| 263 | // load image previews | 262 | // load image previews |
| 264 | { | 263 | { |
| 265 | if let Some(source) = msg.image_preview() { | 264 | let sources = msg |
| 266 | previews.load(source, PreviewKind::Message, worker); | ||
| 267 | } | ||
| 268 | let reply = msg | ||
| 269 | .reply_to() | 265 | .reply_to() |
| 270 | .or_else(|| msg.thread_root()) | 266 | .or_else(|| msg.thread_root()) |
| 271 | .and_then(|e| info.get_event(&e)) | 267 | .and_then(|e| info.get_event(&e)) |
| 272 | .and_then(|msg| msg.image_preview()); | 268 | .into_iter() |
| 273 | if let Some(source) = reply { | 269 | .chain(std::iter::once(msg)) |
| 274 | previews.load(source, PreviewKind::Message, worker); | 270 | .flat_map(|msg| msg.image_previews()); |
| 271 | for (source, kind) in sources { | ||
| 272 | previews.load(source, kind, worker); | ||
| 275 | } | 273 | } |
| 276 | let reactions = | 274 | let reactions = |
| 277 | msg.event.event_id().and_then(|event_id| info.reactions.get(event_id)).map( | 275 | msg.event.event_id().and_then(|event_id| info.reactions.get(event_id)).map( |
| @@ -279,7 +277,7 @@ impl StatefulWidget for MessageWidget<'_> { | |||
| 279 | ); | 277 | ); |
| 280 | if let Some(reactions) = reactions { | 278 | if let Some(reactions) = reactions { |
| 281 | for source in reactions { | 279 | for source in reactions { |
| 282 | previews.load(source, PreviewKind::Reaction, worker); | 280 | previews.load(source, PreviewKind::Emoji, worker); |
| 283 | } | 281 | } |
| 284 | } | 282 | } |
| 285 | } | 283 | } |
| @@ -327,7 +325,7 @@ impl StatefulWidget for MessageWidget<'_> { | |||
| 327 | 325 | ||
| 328 | let proto = match source | 326 | let proto = match source |
| 329 | .as_ref() | 327 | .as_ref() |
| 330 | .and_then(|source| previews.get(source, PreviewKind::Reaction)) | 328 | .and_then(|source| previews.get(source, PreviewKind::Emoji)) |
| 331 | { | 329 | { |
| 332 | Some(ImageStatus::Loaded(backend)) => Some(Some(backend)), | 330 | Some(ImageStatus::Loaded(backend)) => Some(Some(backend)), |
| 333 | // Use empty space as placeholder | 331 | // Use empty space as placeholder |
src/windows/room/scrollback.rs +7 −26
| @@ -158,16 +158,6 @@ impl ScrollbackState { | |||
| 158 | } | 158 | } |
| 159 | } | 159 | } |
| 160 | 160 | ||
| 161 | pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> { | ||
| 162 | let thread = self.get_thread_mut(info); | ||
| 163 | |||
| 164 | if let Some(k) = &self.cursor.timestamp { | ||
| 165 | thread.get_mut(k) | ||
| 166 | } else { | ||
| 167 | thread.last_entry().map(|o| o.into_mut()) | ||
| 168 | } | ||
| 169 | } | ||
| 170 | |||
| 171 | pub fn thread(&self) -> Option<&OwnedEventId> { | 161 | pub fn thread(&self) -> Option<&OwnedEventId> { |
| 172 | self.thread.as_ref() | 162 | self.thread.as_ref() |
| 173 | } | 163 | } |
| @@ -176,10 +166,6 @@ impl ScrollbackState { | |||
| 176 | info.get_thread(self.thread.as_deref()) | 166 | info.get_thread(self.thread.as_deref()) |
| 177 | } | 167 | } |
| 178 | 168 | ||
| 179 | pub fn get_thread_mut<'a>(&self, info: &'a mut RoomInfo) -> &'a mut Messages { | ||
| 180 | info.get_thread_mut(self.thread.clone()) | ||
| 181 | } | ||
| 182 | |||
| 183 | pub fn messages<'a>( | 169 | pub fn messages<'a>( |
| 184 | &self, | 170 | &self, |
| 185 | range: EditRange<MessageCursor>, | 171 | range: EditRange<MessageCursor>, |
| @@ -1368,22 +1354,17 @@ impl StatefulWidget for Scrollback<'_> { | |||
| 1368 | // load image previews | 1354 | // load image previews |
| 1369 | if settings.tunables.image_preview.enabled { | 1355 | if settings.tunables.image_preview.enabled { |
| 1370 | for (key, item) in thread.range(&corner_key..).rev() { | 1356 | for (key, item) in thread.range(&corner_key..).rev() { |
| 1371 | if let Some(source) = item.image_preview() { | 1357 | let previews = item |
| 1372 | self.store.application.previews.load( | ||
| 1373 | source, | ||
| 1374 | PreviewKind::Message, | ||
| 1375 | &self.store.application.worker, | ||
| 1376 | ); | ||
| 1377 | } | ||
| 1378 | let reply = item | ||
| 1379 | .reply_to() | 1358 | .reply_to() |
| 1380 | .or_else(|| item.thread_root()) | 1359 | .or_else(|| item.thread_root()) |
| 1381 | .and_then(|e| info.get_event(&e)) | 1360 | .and_then(|e| info.get_event(&e)) |
| 1382 | .and_then(|msg| msg.image_preview()); | 1361 | .into_iter() |
| 1383 | if let Some(source) = reply { | 1362 | .chain(std::iter::once(item)) |
| 1363 | .flat_map(|msg| msg.image_previews()); | ||
| 1364 | for (source, kind) in previews { | ||
| 1384 | self.store.application.previews.load( | 1365 | self.store.application.previews.load( |
| 1385 | source, | 1366 | source, |
| 1386 | PreviewKind::Message, | 1367 | kind, |
| 1387 | &self.store.application.worker, | 1368 | &self.store.application.worker, |
| 1388 | ); | 1369 | ); |
| 1389 | } | 1370 | } |
| @@ -1391,7 +1372,7 @@ impl StatefulWidget for Scrollback<'_> { | |||
| 1391 | for source in info.get_reaction_images(event_id) { | 1372 | for source in info.get_reaction_images(event_id) { |
| 1392 | self.store.application.previews.load( | 1373 | self.store.application.previews.load( |
| 1393 | source, | 1374 | source, |
| 1394 | PreviewKind::Reaction, | 1375 | PreviewKind::Emoji, |
| 1395 | &self.store.application.worker, | 1376 | &self.store.application.worker, |
| 1396 | ); | 1377 | ); |
| 1397 | } | 1378 | } |
src/worker.rs +4 −4
| @@ -518,13 +518,13 @@ fn insert_msgs_and_receipts( | |||
| 518 | info.insert_encrypted(msg); | 518 | info.insert_encrypted(msg); |
| 519 | }, | 519 | }, |
| 520 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => { | 520 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => { |
| 521 | info.insert_with_preview(msg, settings, previews); | 521 | info.insert_message(msg, settings, previews); |
| 522 | }, | 522 | }, |
| 523 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { | 523 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { |
| 524 | info.insert_reaction_with_preview(ev, settings, previews); | 524 | info.insert_reaction_with_preview(ev, settings, previews); |
| 525 | }, | 525 | }, |
| 526 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { | 526 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { |
| 527 | info.insert_sticker_with_preview(ev, settings, previews); | 527 | info.insert_sticker(ev, settings, previews); |
| 528 | }, | 528 | }, |
| 529 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomRedaction(..)) => { | 529 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomRedaction(..)) => { |
| 530 | // ignoring redaction events because we get them bundled with the redacted event | 530 | // ignoring redaction events because we get them bundled with the redacted event |
| @@ -1805,7 +1805,7 @@ impl ClientWorker { | |||
| 1805 | let info = rooms.get_or_default(room_id.to_owned()); | 1805 | let info = rooms.get_or_default(room_id.to_owned()); |
| 1806 | 1806 | ||
| 1807 | let full_ev = ev.into_full_event(room_id.to_owned()); | 1807 | let full_ev = ev.into_full_event(room_id.to_owned()); |
| 1808 | info.insert_with_preview(full_ev, settings, previews); | 1808 | info.insert_message(full_ev, settings, previews); |
| 1809 | 1809 | ||
| 1810 | update_event_receipts(info, &room, event_id).await; | 1810 | update_event_receipts(info, &room, event_id).await; |
| 1811 | } | 1811 | } |
| @@ -1857,7 +1857,7 @@ impl ClientWorker { | |||
| 1857 | let info = rooms.get_or_default(room_id.to_owned()); | 1857 | let info = rooms.get_or_default(room_id.to_owned()); |
| 1858 | 1858 | ||
| 1859 | let full_ev = ev.into_full_event(room_id.to_owned()); | 1859 | let full_ev = ev.into_full_event(room_id.to_owned()); |
| 1860 | info.insert_sticker_with_preview(full_ev, settings, previews); | 1860 | info.insert_sticker(full_ev, settings, previews); |
| 1861 | 1861 | ||
| 1862 | update_event_receipts(info, &room, event_id).await; | 1862 | update_event_receipts(info, &room, event_id).await; |
| 1863 | } | 1863 | } |