Move android port code to servoshell (#32533)

Signed-off-by: Jonathan Schwender <jonathan.schwender@huawei.com>
Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>
This commit is contained in:
Jonathan Schwender 2024-06-19 05:34:08 +02:00 committed by GitHub
parent 6f64a5afad
commit 24906e1c21
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 156 additions and 241 deletions

View file

@ -1,53 +0,0 @@
[package]
name = "simpleservo_jniapi"
version.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
publish.workspace = true
build = "build.rs"
[lib]
name = "simpleservo"
crate-type = ["cdylib"]
test = false
bench = false
[dependencies]
android_logger = "0.14"
getopts = { workspace = true }
ipc-channel = { workspace = true }
jni = "0.21.1"
libc = { workspace = true }
libloading = "0.8"
libservo = { path = "../../components/servo" }
log = { workspace = true }
serde_json = { workspace = true }
servo-media = { workspace = true }
surfman = { workspace = true, features = ["sm-angle-default"] }
webxr = { git = "https://github.com/servo/webxr" }
[build-dependencies]
cc = "1.0"
gl_generator = "0.14"
serde_json = { workspace = true }
vergen = { version = "8.0.0", features = ["git", "gitcl"] }
[features]
debugmozjs = ["libservo/debugmozjs"]
# TODO: Once the native-bluetooth feature works for
# Android, re-add it here.
default = ["max_log_level", "webdriver"]
googlevr = ["libservo/googlevr"]
jitspew = ["libservo/jitspew"]
js_backtrace = ["libservo/js_backtrace"]
max_log_level = ["log/release_max_level_info"]
media-gstreamer = ["libservo/media-gstreamer"]
native-bluetooth = ["libservo/native-bluetooth"]
dynamic_freetype = ["libservo/dynamic_freetype"]
no-wgl = ["libservo/no-wgl"]
profilemozjs = ["libservo/profilemozjs"]
refcell_backtrace = ["libservo/refcell_backtrace"]
webdriver = ["libservo/webdriver"]
webgl_backtrace = ["libservo/webgl_backtrace"]
xr-profile = ["libservo/xr-profile"]

View file

@ -1,54 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use gl_generator::{Api, Fallbacks, Profile, Registry};
use serde_json::{self, Value};
use vergen::EmitBuilder;
fn main() {
let target = env::var("TARGET").unwrap();
let dest = PathBuf::from(&env::var("OUT_DIR").unwrap());
if let Err(error) = EmitBuilder::builder()
.fail_on_error()
.git_sha(true /* short */)
.emit()
{
println!(
"cargo:warning=Could not generate git version information: {:?}",
error
);
println!("cargo:rustc-env=VERGEN_GIT_SHA=nogit");
}
// Generate GL bindings. For now, we only support EGL.
if target.contains("android") {
let mut file = File::create(dest.join("egl_bindings.rs")).unwrap();
Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, [])
.write_bindings(gl_generator::StaticStructGenerator, &mut file)
.unwrap();
println!("cargo:rustc-link-lib=EGL");
}
// FIXME: We need this workaround since jemalloc-sys still links
// to libgcc instead of libunwind, but Android NDK 23c and above
// don't have libgcc. We can't disable jemalloc for Android as
// in 64-bit aarch builds, the system allocator uses tagged
// pointers by default which causes the assertions in SM & mozjs
// to fail. See https://github.com/servo/servo/issues/32175.
let mut libgcc = File::create(dest.join("libgcc.a")).unwrap();
libgcc.write_all(b"INPUT(-lunwind)").unwrap();
println!("cargo:rustc-link-search=native={}", dest.display());
let mut default_prefs = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
default_prefs.push("../../resources/prefs.json");
let prefs: Value = serde_json::from_reader(File::open(&default_prefs).unwrap()).unwrap();
let file = File::create(dest.join("prefs.json")).unwrap();
serde_json::to_writer(file, &prefs).unwrap();
}

View file

@ -1,56 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
pub type ServoGl = std::rc::Rc<dyn servo::gl::Gl>;
#[cfg(any(target_os = "android", target_os = "windows"))]
#[allow(non_camel_case_types)]
pub mod egl {
use std::ffi::CString;
use std::os::raw::c_void;
use log::info;
use servo::gl::GlesFns;
pub type EGLNativeWindowType = *const libc::c_void;
pub type khronos_utime_nanoseconds_t = khronos_uint64_t;
pub type khronos_uint64_t = u64;
pub type khronos_ssize_t = libc::c_long;
pub type EGLint = i32;
pub type EGLContext = *const libc::c_void;
pub type EGLNativeDisplayType = *const libc::c_void;
pub type EGLNativePixmapType = *const libc::c_void;
pub type NativeDisplayType = EGLNativeDisplayType;
pub type NativePixmapType = EGLNativePixmapType;
pub type NativeWindowType = EGLNativeWindowType;
include!(concat!(env!("OUT_DIR"), "/egl_bindings.rs"));
pub struct EGLInitResult {
pub gl_wrapper: crate::gl_glue::ServoGl,
pub gl_context: EGLContext,
pub display: EGLNativeDisplayType,
}
pub fn init() -> Result<EGLInitResult, &'static str> {
info!("Loading EGL...");
unsafe {
let egl = Egl;
let display = egl.GetCurrentDisplay();
egl.SwapInterval(display, 1);
let egl = GlesFns::load_with(|addr| {
let addr = CString::new(addr.as_bytes()).unwrap();
let addr = addr.as_ptr();
let egl = Egl;
egl.GetProcAddress(addr) as *const c_void
});
info!("EGL loaded");
Ok(EGLInitResult {
gl_wrapper: egl,
gl_context: Egl.GetCurrentContext(),
display,
})
}
}
}

View file

@ -17,8 +17,16 @@ name = "servo"
path = "main.rs"
bench = false
# Some of these dependencies are only needed for a specific target os, but
# since build-scripts can't detect the cargo target os at build-time, we
# must unconditionally add these dependencies. See https://github.com/rust-lang/cargo/issues/4932
[build-dependencies]
vergen = { version = "8.3.1", features = ["git", "git2"] }
# Android and OpenHarmony
gl_generator = "0.14"
# Android only
serde_json = { workspace = true }
# MacOS only
cc = "1.0"
[target.'cfg(windows)'.build-dependencies]
@ -47,26 +55,37 @@ webgl_backtrace = ["libservo/webgl_backtrace"]
xr-profile = ["libservo/xr-profile"]
[dependencies]
# For optional feature servo_allocator/use-system-allocator
servo_allocator = { path = "../../components/allocator" }
libc = { workspace = true }
libservo = { path = "../../components/servo" }
cfg-if = { workspace = true }
log = { workspace = true }
url = { workspace = true }
lazy_static = { workspace = true }
getopts = { workspace = true }
url = { workspace = true }
[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.14"
ipc-channel = { workspace = true }
jni = "0.21.1"
libloading = "0.8"
serde_json = { workspace = true }
servo-media = { workspace = true }
surfman = { workspace = true, features = ["sm-angle-default"] }
webxr = { git = "https://github.com/servo/webxr" }
[target.'cfg(not(target_os = "android"))'.dependencies]
backtrace = { workspace = true }
getopts = { workspace = true }
[target.'cfg(target_env = "ohos")'.dependencies]
# force inprocess, until libc-rs is updated to include `shm_open` and unlink.
# force inprocess, until libc-rs 0.2.156 is released containing
# https://github.com/rust-lang/libc/commit/9e248e212c5602cb4e98676e4c21ea0382663a12
ipc-channel = { workspace = true, features = ["force-inprocess"] }
[target.'cfg(not(any(target_os = "android", target_env = "ohos")))'.dependencies]
# For optional feature servo_allocator/use-system-allocator
servo_allocator = { path = "../../components/allocator" }
arboard = { version = "3" }
egui = { version = "0.26.2" }
egui_glow = { version = "0.26.2", features = ["winit"] }

View file

@ -3,8 +3,12 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::error::Error;
use std::path::Path;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use gl_generator::{Api, Fallbacks, Profile, Registry};
use serde_json::Value;
use vergen::EmitBuilder;
fn main() -> Result<(), Box<dyn Error>> {
@ -39,6 +43,29 @@ fn main() -> Result<(), Box<dyn Error>> {
cc::Build::new()
.file("platform/macos/count_threads.c")
.compile("count_threads");
} else if target_os == "android" {
// Generate GL bindings. For now, we only support EGL.
let mut file = File::create(out.join("egl_bindings.rs")).unwrap();
Registry::new(Api::Egl, (1, 5), Profile::Core, Fallbacks::All, [])
.write_bindings(gl_generator::StaticStructGenerator, &mut file)
.unwrap();
println!("cargo:rustc-link-lib=EGL");
// FIXME: We need this workaround since jemalloc-sys still links
// to libgcc instead of libunwind, but Android NDK 23c and above
// don't have libgcc. We can't disable jemalloc for Android as
// in 64-bit aarch builds, the system allocator uses tagged
// pointers by default which causes the assertions in SM & mozjs
// to fail. See https://github.com/servo/servo/issues/32175.
let mut libgcc = File::create(out.join("libgcc.a")).unwrap();
libgcc.write_all(b"INPUT(-lunwind)").unwrap();
println!("cargo:rustc-link-search=native={}", out.display());
let mut default_prefs = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
default_prefs.push("../../resources/prefs.json");
let prefs: Value = serde_json::from_reader(File::open(&default_prefs).unwrap()).unwrap();
let file = File::create(out.join("prefs.json")).unwrap();
serde_json::to_writer(file, &prefs).unwrap();
}
if let Err(error) = EmitBuilder::builder()

View file

@ -4,7 +4,6 @@
#![allow(non_snake_case)]
mod gl_glue;
mod simpleservo;
use std::collections::HashMap;
@ -23,6 +22,8 @@ use simpleservo::{
MediaSessionPlaybackState, PromptResult, ServoGlue, SERVO,
};
use super::gl_glue;
struct HostCallbacks {
callbacks: GlobalRef,
jvm: JavaVM,
@ -35,7 +36,7 @@ extern "C" {
#[no_mangle]
pub extern "C" fn android_main() {
// FIXME(mukilan): this android_main is only present to stop
// the java side 'System.loadLibrary('simpleservo') call from
// the java side 'System.loadLibrary('servoshell') call from
// failing due to undefined reference to android_main introduced
// by winit's android-activity crate. There is no way to disable
// this currently.
@ -60,7 +61,7 @@ pub extern "C" fn Java_org_mozilla_servoview_JNIServo_version<'local>(
mut env: JNIEnv<'local>,
_class: JClass<'local>,
) -> JString<'local> {
let v = simpleservo::servo_version();
let v = crate::servo_version();
env.new_string(&v)
.unwrap_or_else(|_str| JObject::null().into())
}
@ -88,9 +89,8 @@ pub extern "C" fn Java_org_mozilla_servoview_JNIServo_init<'local>(
// should show up in adb logcat with a release build.
let filters = [
"servo",
"simpleservo",
"simpleservo::jniapi",
"simpleservo::gl_glue::egl",
"servoshell",
"servoshell::egl:gl_glue",
// Show JS errors by default.
"script::dom::bindings::error",
// Show GL errors by default.
@ -112,7 +112,7 @@ pub extern "C" fn Java_org_mozilla_servoview_JNIServo_init<'local>(
Config::default()
.with_max_level(log::LevelFilter::Debug)
.with_filter(filter_builder.build())
.with_tag("simpleservo"),
.with_tag("servoshell"),
)
}
@ -134,7 +134,7 @@ pub extern "C" fn Java_org_mozilla_servoview_JNIServo_init<'local>(
let wakeup = Box::new(WakeupCallback::new(callbacks_ref.clone(), &env));
let callbacks = Box::new(HostCallbacks::new(callbacks_ref, &env));
if let Err(err) = gl_glue::egl::init()
if let Err(err) = gl_glue::init()
.and_then(|egl_init| simpleservo::init(opts, egl_init.gl_wrapper, wakeup, callbacks))
{
throw(&mut env, err)
@ -714,7 +714,7 @@ fn redirect_stdout_to_logcat() {
let mut cursor = 0_usize;
let tag = b"simpleservo\0".as_ptr() as _;
let tag = b"servoshell\0".as_ptr() as _;
loop {
let result = {
@ -893,7 +893,7 @@ fn get_options<'local>(
let gst_debug_str = get_field_as_string(env, opts, "gstDebugStr")?;
let density = get_non_null_field(env, opts, "density", "F")?
.f()
.map_err(|_| "densitiy not a float")? as f32;
.map_err(|_| "density not a float")? as f32;
let log = get_non_null_field(env, opts, "enableLogs", "Z")?
.z()
.map_err(|_| "enableLogs not a boolean")?;

View file

@ -184,14 +184,6 @@ pub struct ServoGlue {
#[derive(Debug)]
pub struct WebView {}
pub fn servo_version() -> String {
format!(
"Servo {}-{}",
env!("CARGO_PKG_VERSION"),
env!("VERGEN_GIT_SHA")
)
}
/// Test if a url is valid.
pub fn is_uri_valid(url: &str) -> bool {
info!("load_uri: {}", url);
@ -926,28 +918,28 @@ impl ResourceReaderMethods for ResourceReaderInstance {
Vec::from(match res {
Resource::Preferences => &include_bytes!(concat!(env!("OUT_DIR"), "/prefs.json"))[..],
Resource::HstsPreloadList => {
&include_bytes!("../../../resources/hsts_preload.json")[..]
&include_bytes!("../../../../resources/hsts_preload.json")[..]
},
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::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")[..]
&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::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")[..]
&include_bytes!("../../../../resources/gatt_blocklist.txt")[..]
},
Resource::MediaControlsCSS => {
&include_bytes!("../../../resources/media-controls.css")[..]
&include_bytes!("../../../../resources/media-controls.css")[..]
},
Resource::MediaControlsJS => {
&include_bytes!("../../../resources/media-controls.js")[..]
&include_bytes!("../../../../resources/media-controls.js")[..]
},
Resource::CrashHTML => &include_bytes!("../../../resources/crash.html")[..],
Resource::CrashHTML => &include_bytes!("../../../../resources/crash.html")[..],
})
}

View file

@ -0,0 +1,53 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![allow(non_camel_case_types)]
pub type ServoGl = std::rc::Rc<dyn servo::gl::Gl>;
use std::ffi::CString;
use std::os::raw::c_void;
use log::info;
use servo::gl::GlesFns;
pub type EGLNativeWindowType = *const libc::c_void;
pub type khronos_utime_nanoseconds_t = khronos_uint64_t;
pub type khronos_uint64_t = u64;
pub type khronos_ssize_t = libc::c_long;
pub type EGLint = i32;
pub type EGLContext = *const libc::c_void;
pub type EGLNativeDisplayType = *const libc::c_void;
pub type EGLNativePixmapType = *const libc::c_void;
pub type NativeDisplayType = EGLNativeDisplayType;
pub type NativePixmapType = EGLNativePixmapType;
pub type NativeWindowType = EGLNativeWindowType;
include!(concat!(env!("OUT_DIR"), "/egl_bindings.rs"));
pub struct EGLInitResult {
pub gl_wrapper: ServoGl,
pub gl_context: EGLContext,
pub display: EGLNativeDisplayType,
}
pub fn init() -> Result<EGLInitResult, &'static str> {
info!("Loading EGL...");
unsafe {
let egl = Egl;
let display = egl.GetCurrentDisplay();
egl.SwapInterval(display, 1);
let egl = GlesFns::load_with(|addr| {
let addr = CString::new(addr.as_bytes()).unwrap();
let addr = addr.as_ptr();
let egl = Egl;
egl.GetProcAddress(addr) as *const c_void
});
info!("EGL loaded");
Ok(EGLInitResult {
gl_wrapper: egl,
gl_context: Egl.GetCurrentContext(),
display,
})
}
}

View file

@ -0,0 +1,9 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[cfg(target_os = "android")]
pub mod gl_glue;
#[cfg(target_os = "android")]
mod android;

View file

@ -2,9 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// For Android, see /support/android/apk/ + /ports/jniapi/.
#![cfg(not(target_os = "android"))]
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[macro_use]
extern crate sig;
@ -12,15 +9,19 @@ extern crate sig;
#[cfg(test)]
mod test;
#[cfg(not(target_os = "android"))]
mod backtrace;
mod crash_handler;
#[cfg(not(any(target_os = "android", target_env = "ohos")))]
pub(crate) mod desktop;
#[cfg(not(target_os = "android"))]
mod panic_hook;
mod parser;
mod prefs;
mod resources;
mod egl;
pub mod platform {
#[cfg(target_os = "macos")]
pub use crate::platform::macos::deinit;
@ -41,7 +42,7 @@ pub fn main() {
pub fn main() {
println!(
"Cannot start /ports/servoshell/ on Android. \
Use /support/android/apk/ + /ports/jniapi/ instead"
Use /support/android/apk/ + `libservoshell.so` instead"
);
}