8000 feat(reader): open a picture in a message in the lightbox on click by adriadam10 · Pull Request #713 · hyprlab/hylki · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

- **New: a picture in a message opens in the lightbox.** A click on a
picture in a message body shows it over the whole window, as an attached
one shows, to zoom in on, save or print. A remote picture is shown from
the copy the reader already loaded, so the click fetches nothing; a
picture inside a link still follows the link, and icons and spacers
smaller than 48 pixels are left alone.

- **New: the address behind a Duck Address** (#708, requested by
somepaulo). Settings → Contacts → Show the address behind a Duck Address
shows a DuckDuckGo Email Protection relay address such as
Expand Down
4 changes: 4 additions & 0 deletions src/app/children.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ fn message_view_output_msg(out: MessageViewOutput) -> AppMsg {
id,
show,
},
MessageViewOutput::ShowImage(att) => AppMsg::ShowLightbox {
items: vec![att],
start: 0,
},
MessageViewOutput::OpenWindow(m) => AppMsg::OpenMessageWindow {
message: *m,
thread: Vec::new(),
Expand Down
2 changes: 2 additions & 0 deletions src/ui/message_view/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@ impl Component for MessageView {
model.watch_loads(&sender);
model.watch_context_menu(&sender);
model.watch_bridge(&sender);
model.watch_image_clicks(&sender);
model.watch_theme(&sender);

let header_tags = gtk::Box::new(gtk::Orientation::Horizontal, 4);
Expand Down Expand Up @@ -532,6 +533,7 @@ impl Component for MessageView {
MessageViewInput::ScrollToAttachments { account_id, id } => {
self.on_scroll_to_attachments(account_id, id)
}
MessageViewInput::ShowImage(uri) => super::links::show_image(&uri, &sender),
MessageViewInput::AttachmentAction {
account_id,
id,
Expand Down
76 changes: 71 additions & 5 deletions src/ui/message_view/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use super::bridge::{parse_bridge, Bridge};
use super::chrome::ClassRules;
use super::links::{is_launchable_uri, link_destination, CLICK_LINK_PROBE};
use super::links::{is_launchable_uri, link_destination, CLICK_IMAGE_PROBE, CLICK_LINK_PROBE};
use super::menu::{menu_lookup, menu_skipped, MenuHit};
use super::types::{ChipAction, MessageViewInput};
use super::MessageView;
Expand Down Expand Up @@ -154,8 +154,15 @@ impl MessageView {
// in the first message that has one, once, a few seconds after a
// conversation is in, and logs what the click landed on. Exercises
// the whole link path (frame → policy decision → launcher, #202)
// without a pointer.
let click_link = std::env::var("HYLKI_SHOWCASE_CLICK_LINK").is_ok();
// without a pointer. HYLKI_SHOWCASE_CLICK_IMAGE=1 clicks the first
// picture instead (frame → bridge → lightbox).
let click_image = std::env::var("HYLKI_SHOWCASE_CLICK_IMAGE").is_ok();
let click_link = click_image || std::env::var("HYLKI_SHOWCASE_CLICK_LINK").is_ok();
let probe = if click_image {
CLICK_IMAGE_PROBE
} else {
CLICK_LINK_PROBE
};
let clicked = std::rc::Rc::new(std::cell::Cell::new(false));
// Bumped per load, so the backstop of a page already replaced can't
// say the next one is ready (and lift its still) before it is.
Expand All @@ -179,19 +186,25 @@ impl MessageView {
if click_link && !clicked.get() {
let view = view.clone();
let clicked = clicked.clone();
let shown = ready_sender.clone();
gtk::glib::timeout_add_local_once(
std::time::Duration::from_secs(4),
8000 move || {
view.evaluate_javascript(
CLICK_LINK_PROBE,
probe,
None,
None,
None::<&gtk::gio::Cancellable>,
move |r| match r {
Ok(v) => {
let text = v.to_str().to_string();
if text.starts_with("clicked") {
if let Some(rest) = text.strip_prefix("clicked ") {
clicked.set(true);
if click_image {
shown.input_sender().emit(
MessageViewInput::ShowImage(rest.to_string()),
);
}
}
tracing::info!("showcase: click-link probe: {text}");
}
Expand Down Expand Up @@ -286,6 +299,59 @@ impl MessageView {
}

/// The `hylki` script-message handler.
/// A click on a picture in a body shows it in the lightbox. The page
/// cannot say so itself: a message's frame runs no script, and a
/// listener the wrapper sets on it is never called. So the click is
/// read here, from what WebKit last said is under the pointer: a
/// single click on a picture that is not a link, the pointer not moved
/// in between (a drag selects text) and no modifier held (those select
/// cards).
pub(super) fn watch_image_clicks(&self, sender: &ComponentSender<Self>) {
let under: std::rc::Rc<std::cell::RefCell<Option<String>>> = Default::default();
self.webview.connect_mouse_target_changed({
let under = under.clone();
move |_view, hit, _modifiers| {
let uri = (hit.context_is_image() && !hit.context_is_link())
.then(|| hit.image_uri())
.flatten()
.map(|u| u.to_string());
under.replace(uri);
}
});
let click = gtk::GestureClick::new();
click.set_propagation_phase(gtk::PropagationPhase::Capture);
let pressed: std::rc::Rc<std::cell::RefCell<Option<String>>> = Default::default();
click.connect_pressed({
let (under, pressed) = (under.clone(), pressed.clone());
move |g, n, _, _| {
let plain = !g.current_event_state().intersects(
gtk::gdk::ModifierType::SHIFT_MASK
| gtk::gdk::ModifierType::CONTROL_MASK
| gtk::gdk::ModifierType::ALT_MASK
| gtk::gdk::ModifierType::META_MASK,
);
let at = (n == 1 && plain && g.current_button() == gtk::gdk::BUTTON_PRIMARY)
.then(|| under.borrow().clone())
.flatten();
pressed.replace(at);
}
});
// Moved past the drag threshold: a selection, not a click.
click.connect_stopped({
let pressed = pressed.clone();
move |_| {
pressed.replace(None);
}
});
let input = sender.input_sender().clone();
click.connect_released(move |_, n, _, _| {
if let Some(uri) = pressed.take().filter(|_| n == 1) {
input.emit(MessageViewInput::ShowImage(uri));
}
});
self.webview.add_controller(click);
}

pub(super) fn watch_bridge(&self, sender: &ComponentSender<Self>) {
// Everything the page posts to the `hylki` handler (see bridge.rs).
if let Some(ucm) = self.webview.user_content_manager() {
Expand Down
58 changes: 58 additions & 0 deletions src/ui/message_view/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ var who=el?el.tagName+(el.className?'.'+el.className:''):'nothing';a.click();\
return 'clicked '+a.href+' at '+Math.round(x)+','+Math.round(y)+' over '+who;}\
return 'no web link in any frame';})()";

/// The HYLKI_SHOWCASE_CLICK_IMAGE probe: the address of the first picture
/// in any message frame, for the reader to show as a click on it would.
pub(super) const CLICK_IMAGE_PROBE: &str =
"(function(){var fs=document.querySelectorAll('iframe.hylki-frame');\
for(var i=0;i<fs.length;i++){var d=fs[i].contentDocument;if(!d)continue;\
var m=d.querySelector('img');if(m)return 'clicked '+m.src;}\
return 'no picture in any frame';})()";

/// Whether a clicked link may be handed to the desktop's default handler.
///
/// An allowlist, not a blocklist: every scheme a desktop registers is a program
Expand Down Expand Up @@ -175,3 +183,53 @@ pub(super) fn remote_image_name(url: &str, content_type: &str) -> String {
}
}
}

/// Show a picture clicked in a message body in the app's lightbox: from the
/// message's own bytes, or from the cache a remote one was shown through, so
/// the click sends nothing new to the sender (as "Save Image As…", #569). A
/// remote picture that was blocked is only an address, and shows nothing,
/// as do icons and spacers smaller than [`MIN_SHOWN`] either way.
pub(super) fn show_image(uri: &str, sender: &relm4::ComponentSender<super::MessageView>) {
let show = |name: &str, data: Vec<u8>, sender: &relm4::ComponentSender<super::MessageView>| {
let small = gtk::gdk::Texture::from_bytes(&gtk::glib::Bytes::from(&data)).is_ok_and(|t| {
use gtk::prelude::TextureExt;
t.width() < MIN_SHOWN || t.height() < MIN_SHOWN
});
if small {
return;
}
// Named by its content, the lightbox routing by extension; an SVG
// has no magic bytes and keeps the name its type gave it.
let name = match name.rsplit_once('.') {
Some((_, "svg")) => name.to_string(),
split => format!(
"{}.{}",
split.map_or(name, |(stem, _)| stem),
crate::models::image_ext(&data)
),
};
let _ = sender.output(super::types::MessageViewOutput::ShowImage(
crate::models::Attachment {
name,
data: data.into(),
},
));
};
if let Some((mime, data)) = own_picture(uri) {
show(&default_image_name(&mime), data, sender);
} else if let Some(web) = crate::services::remote_content::web_url(uri) {
let sender = sender.clone();
crate::services::remote_content::get(uri, move |entry| match entry {
Some(e) => show(
&remote_image_name(&web, &e.content_type),
e.bytes.to_vec(),
&sender,
),
None => tracing::warn!("show image: the picture could not be loaded"),
});
}
}

/// The smallest picture a click shows, in either direction: below it, a
/// logo in a signature, an icon or a tracking pixel.
const MIN_SHOWN: i32 = 48;
5 changes: 5 additions & 0 deletions src/ui/message_view/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ pub(crate) enum MessageViewInput {
account_id: u32,
id: u32,
},
/// A picture in a message body was clicked: its address as the page
/// loaded it (`data:`, a lifted inline picture, or a cached remote one).
ShowImage(String),
/// A card's attachment chip was clicked (open), its save button, or
/// Space was pressed on it (#213, #625).
AttachmentAction {
Expand Down Expand Up @@ -487,6 +490,8 @@ pub(crate) enum MessageViewOutput {
y: f64,
hit: MenuHit,
},
/// Show this picture from a message body in the app's lightbox.
ShowImage(crate::models::Attachment),
/// An email address in a card header was clicked — open a composer to it.
ComposeTo(String),
/// "Add to Contacts" picked on an address's right-click menu.
Expand Down
4 changes: 4 additions & 0 deletions src/ui/message_window/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,5 +452,9 @@ fn from_reader(out: MessageViewOutput) -> MessageWindowInput {
action,
},
MessageViewOutput::AddContactAddr(addr) => MessageWindowInput::AddContactAddr(addr),
MessageViewOutput::ShowImage(att) => MessageWindowInput::Lightbox {
items: vec![att],
start: 0,
},
}
}
0