Auto merge of #22836 - paulrouget:remove_readfile_callback, r=jdm

Remove readfile callback

Reproducing what is done in libmlservo.

This simplifies a lot of things. No need for resources anymore.

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/22836)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2019-02-06 08:20:57 -05:00 committed by GitHub
commit 16b8347c86
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 42 additions and 119 deletions

View file

@ -10,7 +10,7 @@ pub mod gl_glue;
use servo::compositing::windowing::{ use servo::compositing::windowing::{
AnimationState, EmbedderCoordinates, MouseWindowEvent, WindowEvent, WindowMethods, AnimationState, EmbedderCoordinates, MouseWindowEvent, WindowEvent, WindowMethods,
}; };
use servo::embedder_traits::resources::{self, Resource}; use servo::embedder_traits::resources::{self, Resource, ResourceReaderMethods};
use servo::embedder_traits::EmbedderMsg; use servo::embedder_traits::EmbedderMsg;
use servo::euclid::{TypedPoint2D, TypedScale, TypedSize2D, TypedVector2D}; use servo::euclid::{TypedPoint2D, TypedScale, TypedSize2D, TypedVector2D};
use servo::msg::constellation_msg::TraversalDirection; use servo::msg::constellation_msg::TraversalDirection;
@ -42,11 +42,6 @@ pub struct InitOptions {
pub enable_subpixel_text_antialiasing: bool, pub enable_subpixel_text_antialiasing: bool,
} }
/// Delegate resource file reading to the embedder.
pub trait ReadFileTrait {
fn readfile(&self, file: &str) -> Vec<u8>;
}
/// Callbacks. Implemented by embedder. Called by Servo. /// Callbacks. Implemented by embedder. Called by Servo.
pub trait HostTrait { pub trait HostTrait {
/// Will be called from the thread used for the init call. /// Will be called from the thread used for the init call.
@ -112,10 +107,9 @@ pub fn init(
init_opts: InitOptions, init_opts: InitOptions,
gl: Rc<dyn gl::Gl>, gl: Rc<dyn gl::Gl>,
waker: Box<dyn EventLoopWaker>, waker: Box<dyn EventLoopWaker>,
readfile: Box<dyn ReadFileTrait + Send + Sync>,
callbacks: Box<dyn HostTrait>, callbacks: Box<dyn HostTrait>,
) -> Result<(), &'static str> { ) -> Result<(), &'static str> {
resources::set(Box::new(ResourceReader(readfile))); resources::set(Box::new(ResourceReaderInstance::new()));
if let Some(args) = init_opts.args { if let Some(args) = init_opts.args {
let mut args: Vec<String> = serde_json::from_str(&args) let mut args: Vec<String> = serde_json::from_str(&args)
@ -538,31 +532,43 @@ impl WindowMethods for ServoCallbacks {
} }
} }
struct ResourceReader(Box<dyn ReadFileTrait + Send + Sync>); struct ResourceReaderInstance;
impl resources::ResourceReaderMethods for ResourceReader { impl ResourceReaderInstance {
fn read(&self, file: Resource) -> Vec<u8> { fn new() -> ResourceReaderInstance {
let file = match file { ResourceReaderInstance
Resource::Preferences => "prefs.json",
Resource::BluetoothBlocklist => "gatt_blocklist.txt",
Resource::DomainList => "public_domains.txt",
Resource::HstsPreloadList => "hsts_preload.json",
Resource::SSLCertificates => "certs",
Resource::BadCertHTML => "badcert.html",
Resource::NetErrorHTML => "neterror.html",
Resource::UserAgentCSS => "user-agent.css",
Resource::ServoCSS => "servo.css",
Resource::PresentationalHintsCSS => "presentational-hints.css",
Resource::QuirksModeCSS => "quirks-mode.css",
Resource::RippyPNG => "rippy.png",
};
info!("ResourceReader::read({})", file);
self.0.readfile(file)
} }
fn sandbox_access_files_dirs(&self) -> Vec<PathBuf> { }
vec![]
impl ResourceReaderMethods for ResourceReaderInstance {
fn read(&self, res: Resource) -> Vec<u8> {
Vec::from(match res {
Resource::Preferences => &include_bytes!("../../../../resources/prefs.json")[..],
Resource::HstsPreloadList => {
&include_bytes!("../../../../resources/hsts_preload.json")[..]
},
Resource::SSLCertificates => &include_bytes!("../../../../resources/certs")[..],
Resource::BadCertHTML => &include_bytes!("../../../../resources/badcert.html")[..],
Resource::NetErrorHTML => &include_bytes!("../../../../resources/neterror.html")[..],
Resource::UserAgentCSS => &include_bytes!("../../../../resources/user-agent.css")[..],
Resource::ServoCSS => &include_bytes!("../../../../resources/servo.css")[..],
Resource::PresentationalHintsCSS => {
&include_bytes!("../../../../resources/presentational-hints.css")[..]
},
Resource::QuirksModeCSS => &include_bytes!("../../../../resources/quirks-mode.css")[..],
Resource::RippyPNG => &include_bytes!("../../../../resources/rippy.png")[..],
Resource::DomainList => &include_bytes!("../../../../resources/public_domains.txt")[..],
Resource::BluetoothBlocklist => {
&include_bytes!("../../../../resources/gatt_blocklist.txt")[..]
},
})
} }
fn sandbox_access_files(&self) -> Vec<PathBuf> { fn sandbox_access_files(&self) -> Vec<PathBuf> {
vec![] vec![]
} }
fn sandbox_access_files_dirs(&self) -> Vec<PathBuf> {
vec![]
}
} }

View file

@ -5,9 +5,7 @@
#[macro_use] #[macro_use]
extern crate log; extern crate log;
use simpleservo::{ use simpleservo::{self, gl_glue, EventLoopWaker, HostTrait, InitOptions, ServoGlue, SERVO};
self, gl_glue, EventLoopWaker, HostTrait, InitOptions, ReadFileTrait, ServoGlue, SERVO,
};
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::mem; use std::mem;
use std::os::raw::c_char; use std::os::raw::c_char;
@ -68,7 +66,6 @@ fn init(
opts: CInitOptions, opts: CInitOptions,
gl: gl_glue::ServoGl, gl: gl_glue::ServoGl,
wakeup: extern "C" fn(), wakeup: extern "C" fn(),
readfile: extern "C" fn(*const c_char) -> *const c_char,
callbacks: CHostCallbacks, callbacks: CHostCallbacks,
) { ) {
let args = unsafe { CStr::from_ptr(opts.args) }; let args = unsafe { CStr::from_ptr(opts.args) };
@ -87,10 +84,9 @@ fn init(
}; };
let wakeup = Box::new(WakeupCallback::new(wakeup)); let wakeup = Box::new(WakeupCallback::new(wakeup));
let readfile = Box::new(ReadFileCallback::new(readfile));
let callbacks = Box::new(HostCallbacks::new(callbacks)); let callbacks = Box::new(HostCallbacks::new(callbacks));
simpleservo::init(opts, gl, wakeup, readfile, callbacks).unwrap(); simpleservo::init(opts, gl, wakeup, callbacks).unwrap();
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@ -98,11 +94,10 @@ fn init(
pub extern "C" fn init_with_egl( pub extern "C" fn init_with_egl(
opts: CInitOptions, opts: CInitOptions,
wakeup: extern "C" fn(), wakeup: extern "C" fn(),
readfile: extern "C" fn(*const c_char) -> *const c_char,
callbacks: CHostCallbacks, callbacks: CHostCallbacks,
) { ) {
let gl = gl_glue::egl::init().unwrap(); let gl = gl_glue::egl::init().unwrap();
init(opts, gl, wakeup, readfile, callbacks) init(opts, gl, wakeup, callbacks)
} }
#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
@ -110,11 +105,10 @@ pub extern "C" fn init_with_egl(
pub extern "C" fn init_with_gl( pub extern "C" fn init_with_gl(
opts: CInitOptions, opts: CInitOptions,
wakeup: extern "C" fn(), wakeup: extern "C" fn(),
readfile: extern "C" fn(*const c_char) -> *const c_char,
callbacks: CHostCallbacks, callbacks: CHostCallbacks,
) { ) {
let gl = gl_glue::gl::init().unwrap(); let gl = gl_glue::gl::init().unwrap();
init(opts, gl, wakeup, readfile, callbacks) init(opts, gl, wakeup, callbacks)
} }
#[no_mangle] #[no_mangle]
@ -268,25 +262,6 @@ impl EventLoopWaker for WakeupCallback {
} }
} }
pub struct ReadFileCallback(extern "C" fn(*const c_char) -> *const c_char);
impl ReadFileCallback {
fn new(callback: extern "C" fn(*const c_char) -> *const c_char) -> ReadFileCallback {
ReadFileCallback(callback)
}
}
impl ReadFileTrait for ReadFileCallback {
fn readfile(&self, file: &str) -> Vec<u8> {
debug!("readfile: {}", file);
let file = CString::new(file).expect("Can't create string");
let file_ptr = file.as_ptr();
let content = (self.0)(file_ptr);
let content = unsafe { CStr::from_ptr(content) };
content.to_bytes().to_owned()
}
}
struct HostCallbacks(CHostCallbacks); struct HostCallbacks(CHostCallbacks);
impl HostCallbacks { impl HostCallbacks {

View file

@ -13,11 +13,9 @@ use jni::sys::{jboolean, jfloat, jint, jstring, JNI_TRUE};
use jni::{errors, JNIEnv, JavaVM}; use jni::{errors, JNIEnv, JavaVM};
use libc::{dup2, pipe, read}; use libc::{dup2, pipe, read};
use log::Level; use log::Level;
use simpleservo::{ use simpleservo::{self, gl_glue, EventLoopWaker, HostTrait, InitOptions, ServoGlue, SERVO};
self, gl_glue, EventLoopWaker, HostTrait, InitOptions, ReadFileTrait, ServoGlue, SERVO,
};
use std::os::raw::{c_char, c_int, c_void}; use std::os::raw::{c_char, c_int, c_void};
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use std::thread; use std::thread;
struct HostCallbacks { struct HostCallbacks {
@ -101,11 +99,10 @@ pub fn Java_org_mozilla_servoview_JNIServo_init(
}; };
let wakeup = Box::new(WakeupCallback::new(callbacks_ref.clone(), &env)); let wakeup = Box::new(WakeupCallback::new(callbacks_ref.clone(), &env));
let readfile = Box::new(ReadFileCallback::new(callbacks_ref.clone(), &env));
let callbacks = Box::new(HostCallbacks::new(callbacks_ref, &env)); let callbacks = Box::new(HostCallbacks::new(callbacks_ref, &env));
if let Err(err) = if let Err(err) =
gl_glue::egl::init().and_then(|gl| simpleservo::init(opts, gl, wakeup, readfile, callbacks)) gl_glue::egl::init().and_then(|gl| simpleservo::init(opts, gl, wakeup, callbacks))
{ {
throw(&env, err) throw(&env, err)
}; };
@ -352,39 +349,6 @@ impl EventLoopWaker for WakeupCallback {
} }
} }
pub struct ReadFileCallback {
callback: Mutex<GlobalRef>,
jvm: JavaVM,
}
impl ReadFileCallback {
pub fn new(callback: GlobalRef, env: &JNIEnv) -> ReadFileCallback {
let jvm = env.get_java_vm().unwrap();
let callback = Mutex::new(callback);
ReadFileCallback { callback, jvm }
}
}
impl ReadFileTrait for ReadFileCallback {
fn readfile(&self, file: &str) -> Vec<u8> {
// FIXME: we'd rather use attach_current_thread but it detaches the VM too early.
let env = self.jvm.attach_current_thread_as_daemon().unwrap();
let s = match new_string(&env, &file) {
Ok(s) => s,
Err(_) => return vec![],
};
let s = JValue::from(JObject::from(s));
let array = env.call_method(
self.callback.lock().unwrap().as_obj(),
"readfile",
"(Ljava/lang/String;)[B",
&[s],
);
let array = array.unwrap().l().unwrap().into_inner();
env.convert_byte_array(array).unwrap()
}
}
impl HostCallbacks { impl HostCallbacks {
pub fn new(callbacks: GlobalRef, env: &JNIEnv) -> HostCallbacks { pub fn new(callbacks: GlobalRef, env: &JNIEnv) -> HostCallbacks {
let jvm = env.get_java_vm().unwrap(); let jvm = env.get_java_vm().unwrap();

View file

@ -111,7 +111,6 @@ android {
sourceSets { sourceSets {
main { main {
assets.srcDirs = [rootDir.absolutePath + "/../../../target/android/resources"]
} }
armDebug { armDebug {
jniLibs.srcDirs = [getJniLibsPath(true, 'arm')] jniLibs.srcDirs = [getJniLibsPath(true, 'arm')]

View file

@ -97,8 +97,6 @@ public class JNIServo {
void onHistoryChanged(boolean canGoBack, boolean canGoForward); void onHistoryChanged(boolean canGoBack, boolean canGoForward);
void onShutdownComplete(); void onShutdownComplete();
byte[] readfile(String file);
} }
} }

View file

@ -6,12 +6,9 @@
package org.mozilla.servoview; package org.mozilla.servoview;
import android.app.Activity; import android.app.Activity;
import android.content.res.AssetManager;
import android.content.Context; import android.content.Context;
import android.util.Log; import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; import java.util.concurrent.FutureTask;
@ -20,7 +17,6 @@ import org.mozilla.servoview.JNIServo.ServoOptions;
public class Servo { public class Servo {
private static final String LOGTAG = "Servo"; private static final String LOGTAG = "Servo";
private AssetManager mAssetMgr;
private JNIServo mJNI = new JNIServo(); private JNIServo mJNI = new JNIServo();
private RunCallback mRunCallback; private RunCallback mRunCallback;
private boolean mShuttingDown; private boolean mShuttingDown;
@ -37,8 +33,6 @@ public class Servo {
mRunCallback = runCallback; mRunCallback = runCallback;
mAssetMgr = activity.getResources().getAssets();
mServoCallbacks = new Callbacks(client, gfxcb); mServoCallbacks = new Callbacks(client, gfxcb);
mRunCallback.inGLThread(() -> { mRunCallback.inGLThread(() -> {
@ -262,18 +256,5 @@ public class Servo {
public void onRedrawing(boolean redrawing) { public void onRedrawing(boolean redrawing) {
mRunCallback.inUIThread(() -> mClient.onRedrawing(redrawing)); mRunCallback.inUIThread(() -> mClient.onRedrawing(redrawing));
} }
public byte[] readfile(String file) {
try {
InputStream stream = mAssetMgr.open(file);
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
stream.close();
return bytes;
} catch (IOException e) {
Log.e(LOGTAG, "readfile error: " + e.getMessage());
return null;
}
}
} }
} }