Nacre/src/engine/view.rs

184 lines
5.4 KiB
Rust

//! `View`: a handle on one WebKit web view with the page actions the browser uses. Cheap to clone; the view lives as
//! long as its tab keeps it in the window's stack.
use gtk::prelude::*;
use url::Url;
use webkit::prelude::*;
use super::{JsValue, PageAction, ViewId};
#[derive(Clone)]
pub struct View {
id: ViewId,
pub(crate) web: webkit::WebView,
}
impl PartialEq for View {
fn eq(&self, other: &View) -> bool {
self.id == other.id
}
}
impl View {
pub(crate) fn new(id: ViewId, web: webkit::WebView) -> View {
View { id, web }
}
pub fn id(&self) -> ViewId {
self.id
}
/// The GTK widget, for the window's page stack.
pub fn widget(&self) -> gtk::Widget {
self.web.clone().upcast()
}
pub fn load(&self, url: &Url) {
self.web.load_uri(url.as_str());
}
pub fn url(&self) -> Option<Url> {
self.web.uri().and_then(|u| Url::parse(&u).ok())
}
pub fn title(&self) -> Option<String> {
self.web.title().map(|t| t.to_string()).filter(|t| !t.is_empty())
}
pub fn can_go_back(&self) -> bool {
self.web.can_go_back()
}
pub fn can_go_forward(&self) -> bool {
self.web.can_go_forward()
}
pub fn go_back(&self) {
self.web.go_back();
}
pub fn go_forward(&self) {
self.web.go_forward();
}
/// Go `delta` steps in the back/forward list (negative: back).
pub fn go_to(&self, delta: i32) {
let list = self.web.back_forward_list();
if let Some(item) = list.and_then(|l| l.nth_item(delta)) {
self.web.go_to_back_forward_list_item(&item);
}
}
pub fn reload(&self) {
self.web.reload();
}
pub fn reload_bypass_cache(&self) {
self.web.reload_bypass_cache();
}
pub fn stop(&self) {
self.web.stop_loading();
}
pub fn is_loading(&self) -> bool {
self.web.is_loading()
}
pub fn progress(&self) -> f64 {
self.web.estimated_load_progress()
}
pub fn set_page_zoom(&self, zoom: f32) {
self.web.set_zoom_level(zoom as f64);
}
pub fn set_muted(&self, muted: bool) {
self.web.set_is_muted(muted);
}
pub fn is_playing_audio(&self) -> bool {
self.web.is_playing_audio()
}
pub fn focus(&self) {
self.web.grab_focus();
}
pub fn focused(&self) -> bool {
self.web.has_focus()
}
pub fn show_inspector(&self) {
if let Some(inspector) = self.web.inspector() {
inspector.show();
}
}
pub fn close(&self) {
self.web.try_close();
}
/// Back/forward list as URLs and the current index.
pub fn back_forward(&self) -> (Vec<Url>, usize) {
let Some(list) = self.web.back_forward_list() else { return (Vec::new(), 0) };
let parse = |item: &webkit::BackForwardListItem| item.uri().and_then(|u| Url::parse(&u).ok());
// back_list is nearest first
let mut entries: Vec<Url> = list.back_list().iter().rev().filter_map(parse).collect();
let current = entries.len();
if let Some(url) = list.current_item().as_ref().and_then(parse) {
entries.push(url);
}
entries.extend(list.forward_list().iter().filter_map(parse));
(entries, current)
}
/// The favicon as RGBA pixels.
pub fn favicon_rgba(&self) -> Option<(u32, u32, Vec<u8>)> {
let texture = self.web.favicon()?;
let mut downloader = gtk::gdk::TextureDownloader::new(&texture);
downloader.set_format(gtk::gdk::MemoryFormat::R8g8b8a8);
let (bytes, stride) = downloader.download_bytes();
let (w, h) = (texture.width() as usize, texture.height() as usize);
let mut rgba = Vec::with_capacity(w * h * 4);
for row in 0..h {
rgba.extend_from_slice(bytes.get(row * stride..row * stride + w * 4)?);
}
Some((w as u32, h as u32, rgba))
}
pub fn execute(&self, action: PageAction) {
match action {
PageAction::GoBack => self.go_back(),
PageAction::GoForward => self.go_forward(),
PageAction::Reload => self.reload(),
PageAction::Cut => self.web.execute_editing_command("Cut"),
PageAction::Copy => self.web.execute_editing_command("Copy"),
PageAction::Paste => self.web.execute_editing_command("Paste"),
PageAction::SelectAll => self.web.execute_editing_command("SelectAll"),
}
}
/// Run `script` in the page's main frame; `done` gets the completion value as JSON, or the error text.
/// Open WebKit's print dialog for the page.
pub fn print(&self, parent: &gtk::Window) {
let op = webkit::PrintOperation::new(&self.web);
op.run_dialog(Some(parent));
}
pub fn evaluate_javascript(&self, script: impl AsRef<str>, done: impl FnOnce(Result<JsValue, String>) + 'static) {
self.web.evaluate_javascript(script.as_ref(), None, None, None::<&gtk::gio::Cancellable>, move |result| {
done(match result {
Ok(value) => Ok(js_to_json(&value)),
Err(e) => Err(e.to_string()),
})
});
}
}
pub(crate) fn js_to_json(value: &webkit::javascriptcore::Value) -> JsValue {
if value.is_undefined() || value.is_null() {
return JsValue::Null;
}
value.to_json(0).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(JsValue::Null)
}