Commit df3148b9f5

df3148b9f57029a6b6197454f00ab0046ac92dea

parent: 95af00ba93

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-10-08 01:24 UTC

Links should be "openable" (#43)

Layout: unified · split

src/base.rs +7
@@ -274,6 +274,9 @@ pub enum IambAction {
274274 /// Perform an action on the currently selected message.
275275 Message(MessageAction),
276276
277 /// Open a URL.
278 OpenLink(String),
279
277280 /// Perform an action on the currently focused room.
278281 Room(RoomAction),
279282
@@ -327,6 +330,7 @@ impl ApplicationAction for IambAction {
327330 IambAction::Homeserver(..) => SequenceStatus::Break,
328331 IambAction::Message(..) => SequenceStatus::Break,
329332 IambAction::Room(..) => SequenceStatus::Break,
333 IambAction::OpenLink(..) => SequenceStatus::Break,
330334 IambAction::Send(..) => SequenceStatus::Break,
331335 IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
332336 IambAction::Verify(..) => SequenceStatus::Break,
@@ -338,6 +342,7 @@ impl ApplicationAction for IambAction {
338342 match self {
339343 IambAction::Homeserver(..) => SequenceStatus::Atom,
340344 IambAction::Message(..) => SequenceStatus::Atom,
345 IambAction::OpenLink(..) => SequenceStatus::Atom,
341346 IambAction::Room(..) => SequenceStatus::Atom,
342347 IambAction::Send(..) => SequenceStatus::Atom,
343348 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
@@ -351,6 +356,7 @@ impl ApplicationAction for IambAction {
351356 IambAction::Homeserver(..) => SequenceStatus::Ignore,
352357 IambAction::Message(..) => SequenceStatus::Ignore,
353358 IambAction::Room(..) => SequenceStatus::Ignore,
359 IambAction::OpenLink(..) => SequenceStatus::Ignore,
354360 IambAction::Send(..) => SequenceStatus::Ignore,
355361 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
356362 IambAction::Verify(..) => SequenceStatus::Ignore,
@@ -364,6 +370,7 @@ impl ApplicationAction for IambAction {
364370 IambAction::Message(..) => false,
365371 IambAction::Room(..) => false,
366372 IambAction::Send(..) => false,
373 IambAction::OpenLink(..) => false,
367374 IambAction::ToggleScrollbackFocus => false,
368375 IambAction::Verify(..) => false,
369376 IambAction::VerifyRequest(..) => false,
src/main.rs +8
@@ -528,6 +528,14 @@ impl Application {
528528 self.screen.current_window_mut()?.send_command(act, ctx, store).await?
529529 },
530530
531 IambAction::OpenLink(url) => {
532 tokio::task::spawn_blocking(move || {
533 return open::that(url);
534 });
535
536 None
537 },
538
531539 IambAction::Verify(act, user_dev) => {
532540 if let Some(sas) = store.application.verifications.get(&user_dev) {
533541 self.worker.verify(act, sas.clone())?
src/message/html.rs +179 −49
@@ -15,6 +15,7 @@ use std::ops::Deref;
1515use css_color_parser::Color as CssColor;
1616use markup5ever_rcdom::{Handle, NodeData, RcDom};
1717use unicode_segmentation::UnicodeSegmentation;
18use url::Url;
1819
1920use html5ever::{
2021 driver::{parse_fragment, ParseOpts},
@@ -102,6 +103,12 @@ pub struct TableRow {
102103}
103104
104105impl TableRow {
106 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
107 for (_, cell) in &self.cells {
108 cell.gather_links(urls);
109 }
110 }
111
105112 fn columns(&self) -> usize {
106113 self.cells.len()
107114 }
@@ -113,6 +120,12 @@ pub struct TableSection {
113120}
114121
115122impl TableSection {
123 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
124 for row in &self.rows {
125 row.gather_links(urls);
126 }
127 }
128
116129 fn columns(&self) -> usize {
117130 self.rows.iter().map(TableRow::columns).max().unwrap_or(0)
118131 }
@@ -129,6 +142,12 @@ impl Table {
129142 self.sections.iter().map(TableSection::columns).max().unwrap_or(0)
130143 }
131144
145 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
146 for section in &self.sections {
147 section.gather_links(urls);
148 }
149 }
150
132151 fn to_text(&self, width: usize, style: Style) -> Text {
133152 let mut text = Text::default();
134153 let columns = self.columns();
@@ -237,6 +256,7 @@ impl Table {
237256
238257/// A processed HTML element that we can render to the terminal.
239258pub enum StyleTreeNode {
259 Anchor(Box<StyleTreeNode>, char, Url),
240260 Blockquote(Box<StyleTreeNode>),
241261 Break,
242262 Code(Box<StyleTreeNode>, Option<String>),
@@ -260,10 +280,51 @@ impl StyleTreeNode {
260280 printer.finish()
261281 }
262282
283 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
284 match self {
285 StyleTreeNode::Anchor(_, c, url) => {
286 urls.push((*c, url.clone()));
287 },
288
289 StyleTreeNode::Blockquote(child) |
290 StyleTreeNode::Code(child, _) |
291 StyleTreeNode::Header(child, _) |
292 StyleTreeNode::Paragraph(child) |
293 StyleTreeNode::Pre(child) |
294 StyleTreeNode::Reply(child) |
295 StyleTreeNode::Style(child, _) => {
296 child.gather_links(urls);
297 },
298
299 StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => {
300 for child in children {
301 child.gather_links(urls);
302 }
303 },
304
305 StyleTreeNode::Table(table) => {
306 table.gather_links(urls);
307 },
308
309 StyleTreeNode::Image(_) => {},
310 StyleTreeNode::Ruler => {},
311 StyleTreeNode::Text(_) => {},
312 StyleTreeNode::Break => {},
313 }
314 }
315
263316 pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) {
264317 let width = printer.width();
265318
266319 match self {
320 StyleTreeNode::Anchor(child, c, _) => {
321 let bold = style.add_modifier(StyleModifier::BOLD);
322 child.print(printer, bold);
323
324 let link = format!("[{c}]");
325 let span = Span::styled(link, style);
326 printer.push_span_nobreak(span);
327 },
267328 StyleTreeNode::Blockquote(child) => {
268329 let mut subp = printer.sub(4);
269330 child.print(&mut subp, style);
@@ -393,6 +454,16 @@ pub struct StyleTree {
393454}
394455
395456impl StyleTree {
457 pub fn get_links(&self) -> Vec<(char, Url)> {
458 let mut links = Vec::new();
459
460 for child in &self.children {
461 child.gather_links(&mut links);
462 }
463
464 return links;
465 }
466
396467 pub fn to_text(&self, width: usize, style: Style, hide_reply: bool) -> Text<'_> {
397468 let mut printer = TextPrinter::new(width, style, hide_reply);
398469
@@ -404,17 +475,41 @@ impl StyleTree {
404475 }
405476}
406477
407fn c2c(handles: &[Handle]) -> Vec<StyleTreeNode> {
408 handles.iter().flat_map(h2t).collect()
478pub struct TreeGenState {
479 link_num: u8,
409480}
410481
411fn c2t(handles: &[Handle]) -> Box<StyleTreeNode> {
412 let node = StyleTreeNode::Sequence(c2c(handles));
482impl TreeGenState {
483 fn next_link_char(&mut self) -> Option<char> {
484 let num = self.link_num;
485
486 if num < 62 {
487 self.link_num = num + 1;
488 }
489
490 if num < 10 {
491 Some((num + b'0') as char)
492 } else if num < 36 {
493 Some((num - 10 + b'a') as char)
494 } else if num < 62 {
495 Some((num - 36 + b'A') as char)
496 } else {
497 None
498 }
499 }
500}
501
502fn c2c(handles: &[Handle], state: &mut TreeGenState) -> Vec<StyleTreeNode> {
503 handles.iter().flat_map(|h| h2t(h, state)).collect()
504}
505
506fn c2t(handles: &[Handle], state: &mut TreeGenState) -> Box<StyleTreeNode> {
507 let node = StyleTreeNode::Sequence(c2c(handles, state));
413508
414509 Box::new(node)
415510}
416511
417fn get_node(hdl: &Handle, want: &str) -> Option<StyleTreeNode> {
512fn get_node(hdl: &Handle, want: &str, state: &mut TreeGenState) -> Option<StyleTreeNode> {
418513 let node = hdl.deref();
419514
420515 if let NodeData::Element { name, .. } = &node.data {
@@ -422,26 +517,26 @@ fn get_node(hdl: &Handle, want: &str) -> Option<StyleTreeNode> {
422517 return None;
423518 }
424519
425 let c = c2c(&node.children.borrow());
520 let c = c2c(&node.children.borrow(), state);
426521 return Some(StyleTreeNode::Sequence(c));
427522 } else {
428523 return None;
429524 }
430525}
431526
432fn li2t(hdl: &Handle) -> Option<StyleTreeNode> {
433 get_node(hdl, "li")
527fn li2t(hdl: &Handle, state: &mut TreeGenState) -> Option<StyleTreeNode> {
528 get_node(hdl, "li", state)
434529}
435530
436fn table_cell(hdl: &Handle) -> Option<(CellType, StyleTreeNode)> {
437 if let Some(node) = get_node(hdl, "th") {
531fn table_cell(hdl: &Handle, state: &mut TreeGenState) -> Option<(CellType, StyleTreeNode)> {
532 if let Some(node) = get_node(hdl, "th", state) {
438533 return Some((CellType::Header, node));
439534 }
440535
441 Some((CellType::Data, get_node(hdl, "td")?))
536 Some((CellType::Data, get_node(hdl, "td", state)?))
442537}
443538
444fn table_row(hdl: &Handle) -> Option<TableRow> {
539fn table_row(hdl: &Handle, state: &mut TreeGenState) -> Option<TableRow> {
445540 let node = hdl.deref();
446541
447542 if let NodeData::Element { name, .. } = &node.data {
@@ -449,20 +544,20 @@ fn table_row(hdl: &Handle) -> Option<TableRow> {
449544 return None;
450545 }
451546
452 let cells = table_cells(&node.children.borrow());
547 let cells = table_cells(&node.children.borrow(), state);
453548 return Some(TableRow { cells });
454549 } else {
455550 return None;
456551 }
457552}
458553
459fn table_section(hdl: &Handle) -> Option<TableSection> {
554fn table_section(hdl: &Handle, state: &mut TreeGenState) -> Option<TableSection> {
460555 let node = hdl.deref();
461556
462557 if let NodeData::Element { name, .. } = &node.data {
463558 match name.local.as_ref() {
464559 "thead" | "tbody" => {
465 let rows = table_rows(&node.children.borrow());
560 let rows = table_rows(&node.children.borrow(), state);
466561
467562 Some(TableSection { rows })
468563 },
@@ -473,20 +568,20 @@ fn table_section(hdl: &Handle) -> Option<TableSection> {
473568 }
474569}
475570
476fn table_cells(handles: &[Handle]) -> Vec<(CellType, StyleTreeNode)> {
477 handles.iter().filter_map(table_cell).collect()
571fn table_cells(handles: &[Handle], state: &mut TreeGenState) -> Vec<(CellType, StyleTreeNode)> {
572 handles.iter().filter_map(|h| table_cell(h, state)).collect()
478573}
479574
480fn table_rows(handles: &[Handle]) -> Vec<TableRow> {
481 handles.iter().filter_map(table_row).collect()
575fn table_rows(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableRow> {
576 handles.iter().filter_map(|h| table_row(h, state)).collect()
482577}
483578
484fn table_sections(handles: &[Handle]) -> Vec<TableSection> {
485 handles.iter().filter_map(table_section).collect()
579fn table_sections(handles: &[Handle], state: &mut TreeGenState) -> Vec<TableSection> {
580 handles.iter().filter_map(|h| table_section(h, state)).collect()
486581}
487582
488fn lic2t(handles: &[Handle]) -> StyleTreeChildren {
489 handles.iter().filter_map(li2t).collect()
583fn lic2t(handles: &[Handle], state: &mut TreeGenState) -> StyleTreeChildren {
584 handles.iter().filter_map(|h| li2t(h, state)).collect()
490585}
491586
492587fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> {
@@ -501,6 +596,18 @@ fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> {
501596 return None;
502597}
503598
599fn attrs_to_href(attrs: &[Attribute]) -> Option<String> {
600 for attr in attrs {
601 if attr.name.local.as_ref() != "href" {
602 continue;
603 }
604
605 return Some(attr.value.to_string());
606 }
607
608 return None;
609}
610
504611fn attrs_to_language(attrs: &[Attribute]) -> Option<String> {
505612 for attr in attrs {
506613 if attr.name.local.as_ref() != "class" {
@@ -541,75 +648,95 @@ fn attrs_to_style(attrs: &[Attribute]) -> Style {
541648 return style;
542649}
543650
544fn h2t(hdl: &Handle) -> StyleTreeChildren {
651fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
545652 let node = hdl.deref();
546653
547654 let tree = match &node.data {
548 NodeData::Document => *c2t(node.children.borrow().as_slice()),
655 NodeData::Document => *c2t(node.children.borrow().as_slice(), state),
549656 NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string()),
550657 NodeData::Element { name, attrs, .. } => {
551658 match name.local.as_ref() {
552659 // Message that this one replies to.
553 "mx-reply" => StyleTreeNode::Reply(c2t(&node.children.borrow())),
660 "mx-reply" => StyleTreeNode::Reply(c2t(&node.children.borrow(), state)),
661
662 // Links
663 "a" => {
664 let c = c2t(&node.children.borrow(), state);
665 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok());
666
667 if let Some(h) = h {
668 if let Some(n) = state.next_link_char() {
669 StyleTreeNode::Anchor(c, n, h)
670 } else {
671 *c
672 }
673 } else {
674 *c
675 }
676 },
554677
555678 // Style change
556679 "b" | "strong" => {
557 let c = c2t(&node.children.borrow());
680 let c = c2t(&node.children.borrow(), state);
558681 let s = Style::default().add_modifier(StyleModifier::BOLD);
559682
560683 StyleTreeNode::Style(c, s)
561684 },
562685 "font" => {
563 let c = c2t(&node.children.borrow());
686 let c = c2t(&node.children.borrow(), state);
564687 let s = attrs_to_style(&attrs.borrow());
565688
566689 StyleTreeNode::Style(c, s)
567690 },
568691 "em" | "i" => {
569 let c = c2t(&node.children.borrow());
692 let c = c2t(&node.children.borrow(), state);
570693 let s = Style::default().add_modifier(StyleModifier::ITALIC);
571694
572695 StyleTreeNode::Style(c, s)
573696 },
574697 "span" => {
575 let c = c2t(&node.children.borrow());
698 let c = c2t(&node.children.borrow(), state);
576699 let s = attrs_to_style(&attrs.borrow());
577700
578701 StyleTreeNode::Style(c, s)
579702 },
580703 "del" | "strike" => {
581 let c = c2t(&node.children.borrow());
704 let c = c2t(&node.children.borrow(), state);
582705 let s = Style::default().add_modifier(StyleModifier::CROSSED_OUT);
583706
584707 StyleTreeNode::Style(c, s)
585708 },
586709 "u" => {
587 let c = c2t(&node.children.borrow());
710 let c = c2t(&node.children.borrow(), state);
588711 let s = Style::default().add_modifier(StyleModifier::UNDERLINED);
589712
590713 StyleTreeNode::Style(c, s)
591714 },
592715
593716 // Lists
594 "ol" => StyleTreeNode::List(lic2t(&node.children.borrow()), ListStyle::Ordered),
595 "ul" => StyleTreeNode::List(lic2t(&node.children.borrow()), ListStyle::Unordered),
717 "ol" => {
718 StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Ordered)
719 },
720 "ul" => {
721 StyleTreeNode::List(lic2t(&node.children.borrow(), state), ListStyle::Unordered)
722 },
596723
597724 // Headers
598 "h1" => StyleTreeNode::Header(c2t(&node.children.borrow()), 1),
599 "h2" => StyleTreeNode::Header(c2t(&node.children.borrow()), 2),
600 "h3" => StyleTreeNode::Header(c2t(&node.children.borrow()), 3),
601 "h4" => StyleTreeNode::Header(c2t(&node.children.borrow()), 4),
602 "h5" => StyleTreeNode::Header(c2t(&node.children.borrow()), 5),
603 "h6" => StyleTreeNode::Header(c2t(&node.children.borrow()), 6),
725 "h1" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 1),
726 "h2" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 2),
727 "h3" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 3),
728 "h4" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 4),
729 "h5" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 5),
730 "h6" => StyleTreeNode::Header(c2t(&node.children.borrow(), state), 6),
604731
605732 // Table
606733 "table" => {
607 let sections = table_sections(&node.children.borrow());
734 let sections = table_sections(&node.children.borrow(), state);
608735 let caption = node
609736 .children
610737 .borrow()
611738 .iter()
612 .find_map(|hdl| get_node(hdl, "caption"))
739 .find_map(|hdl| get_node(hdl, "caption", state))
613740 .map(Box::new);
614741 let table = Table { caption, sections };
615742
@@ -618,16 +745,16 @@ fn h2t(hdl: &Handle) -> StyleTreeChildren {
618745
619746 // Code blocks.
620747 "code" => {
621 let c = c2t(&node.children.borrow());
748 let c = c2t(&node.children.borrow(), state);
622749 let l = attrs_to_language(&attrs.borrow());
623750
624751 StyleTreeNode::Code(c, l)
625752 },
626753
627754 // Other text blocks.
628 "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow())),
629 "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow())),
630 "pre" => StyleTreeNode::Pre(c2t(&node.children.borrow())),
755 "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow(), state)),
756 "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow(), state)),
757 "pre" => StyleTreeNode::Pre(c2t(&node.children.borrow(), state)),
631758
632759 // No children.
633760 "hr" => StyleTreeNode::Ruler,
@@ -636,8 +763,8 @@ fn h2t(hdl: &Handle) -> StyleTreeChildren {
636763 "img" => StyleTreeNode::Image(attrs_to_alt(&attrs.borrow())),
637764
638765 // These don't render in any special way.
639 "a" | "details" | "html" | "summary" | "sub" | "sup" => {
640 *c2t(&node.children.borrow())
766 "details" | "html" | "summary" | "sub" | "sup" => {
767 *c2t(&node.children.borrow(), state)
641768 },
642769
643770 _ => return vec![],
@@ -654,7 +781,10 @@ fn h2t(hdl: &Handle) -> StyleTreeChildren {
654781}
655782
656783fn dom_to_style_tree(dom: RcDom) -> StyleTree {
657 StyleTree { children: h2t(&dom.document) }
784 let mut state = TreeGenState { link_num: 0 };
785 let children = h2t(&dom.document, &mut state);
786
787 StyleTree { children }
658788}
659789
660790/// Parse an HTML document from a string.
src/windows/room/chat.rs +30 −2
@@ -9,6 +9,7 @@ use edit::edit as external_edit;
99use modalkit::editing::store::RegisterError;
1010use std::process::Command;
1111use tokio;
12use url::Url;
1213
1314use matrix_sdk::{
1415 attachment::AttachmentConfig,
@@ -31,7 +32,7 @@ use matrix_sdk::{
3132};
3233
3334use modalkit::{
34 input::dialog::PromptYesNo,
35 input::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo},
3536 tui::{
3637 buffer::Buffer,
3738 layout::Rect,
@@ -203,7 +204,34 @@ impl ChatState {
203204 MessageType::Image(c) => (c.source.clone(), c.body.as_str()),
204205 MessageType::Video(c) => (c.source.clone(), c.body.as_str()),
205206 _ => {
206 return Err(IambError::NoAttachment.into());
207 if !flags.contains(DownloadFlags::OPEN) {
208 return Err(IambError::NoAttachment.into());
209 }
210
211 let links = if let Some(html) = &msg.html {
212 html.get_links()
213 } else if let Ok(url) = Url::parse(&msg.event.body()) {
214 vec![('0', url)]
215 } else {
216 vec![]
217 };
218
219 if links.is_empty() {
220 return Err(IambError::NoAttachment.into());
221 }
222
223 let choices = links
224 .into_iter()
225 .map(|l| {
226 let url = l.1.to_string();
227 let act = IambAction::OpenLink(url.clone()).into();
228 MultiChoiceItem::new(l.0, url, vec![act])
229 })
230 .collect();
231 let dialog = MultiChoice::new(choices);
232 let err = UIError::NeedConfirm(Box::new(dialog));
233
234 return Err(err);
207235 },
208236 };
209237