| 1 | use gpui_kit::*; |
| 2 | |
| 3 | #[derive(Clone, Copy)] |
| 4 | pub struct RenderHooks { |
| 5 | pub open_profile_link: fn(&str, Point<Pixels>, &mut App) -> bool, |
| 6 | pub jump_to_quoted: fn(String, &mut App), |
| 7 | pub inline_image: fn(&str, &App) -> Option<std::path::PathBuf>, |
| 8 | pub open_link: fn(&str, &mut App), |
| 9 | } |
| 10 | |
| 11 | impl Global for RenderHooks {} |
| 12 | |
| 13 | pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bool { |
| 14 | match cx.try_global::<RenderHooks>().copied() { |
| 15 | Some(hooks) => (hooks.open_profile_link)(url, position, cx), |
| 16 | None => false, |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | const OPENABLE_SCHEMES: [&str; 16] = [ |
| 21 | "https://", |
| 22 | "http://", |
| 23 | "mailto:", |
| 24 | "tel:", |
| 25 | "sip:", |
| 26 | "callto:", |
| 27 | "msteams:", |
| 28 | "onenote:", |
| 29 | "ms-word:", |
| 30 | "ms-excel:", |
| 31 | "ms-powerpoint:", |
| 32 | "ms-visio:", |
| 33 | "ms-access:", |
| 34 | "ms-project:", |
| 35 | "ms-publisher:", |
| 36 | "ms-infopath:", |
| 37 | ]; |
| 38 | |
| 39 | pub fn is_openable_link(url: &str) -> bool { |
| 40 | let lower = url.trim_start().to_ascii_lowercase(); |
| 41 | OPENABLE_SCHEMES |
| 42 | .iter() |
| 43 | .any(|scheme| lower.starts_with(scheme)) |
| 44 | } |
| 45 | |
| 46 | pub fn open_link(url: &str, cx: &mut App) { |
| 47 | if !is_openable_link(url) { |
| 48 | return; |
| 49 | } |
| 50 | match cx.try_global::<RenderHooks>().copied() { |
| 51 | Some(hooks) => (hooks.open_link)(url, cx), |
| 52 | None => cx.open_url(url), |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | pub fn jump_to_quoted(message_id: String, cx: &mut App) { |
| 57 | if let Some(hooks) = cx.try_global::<RenderHooks>().copied() { |
| 58 | (hooks.jump_to_quoted)(message_id, cx); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub fn inline_image(url: &str, cx: &App) -> Option<std::path::PathBuf> { |
| 63 | let hooks = cx.try_global::<RenderHooks>().copied()?; |
| 64 | (hooks.inline_image)(url, cx) |
| 65 | } |
| 66 | |
| 67 | #[cfg(test)] |
| 68 | mod tests { |
| 69 | use super::is_openable_link; |
| 70 | |
| 71 | #[test] |
| 72 | fn only_web_mail_phone_and_teams_links_open() { |
| 73 | assert!(is_openable_link("https://example.test/a")); |
| 74 | assert!(is_openable_link(" HTTP://example.test")); |
| 75 | assert!(is_openable_link("mailto:someone@example.test")); |
| 76 | assert!(is_openable_link("msteams:/l/chat/0/0")); |
| 77 | assert!(is_openable_link( |
| 78 | "ms-word:ofe|u|https://example.test/a.docx" |
| 79 | )); |
| 80 | assert!(!is_openable_link("file:///etc/passwd")); |
| 81 | assert!(!is_openable_link("search-ms:query=x")); |
| 82 | assert!(!is_openable_link("javascript:alert(1)")); |
| 83 | assert!(!is_openable_link("//example.test")); |
| 84 | } |
| 85 | } |