OHOS: Use native API to get most of the information needed for starting servoshell. (#37392)

Uses the native ohos-api crates to get the required information for
starting servoshell.
This increases the minimum API version requirement to API-14.

Testing: Tested on device.

---------

Signed-off-by: Narfinger <Narfinger@users.noreply.github.com>
Co-authored-by: Jonathan Schwender <55576758+jschwe@users.noreply.github.com>
This commit is contained in:
Narfinger 2025-06-13 11:38:56 +02:00 committed by GitHub
parent 7a801f0ef5
commit 099fd10317
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 95 additions and 47 deletions

36
Cargo.lock generated
View file

@ -5391,6 +5391,30 @@ dependencies = [
"memchr",
]
[[package]]
name = "ohos-abilitykit-sys"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ff6fba3cf019d0dcabc3ee41396a7180b9b6fd64bee904a27144224a9be81c7"
dependencies = [
"ohos-sys-opaque-types",
]
[[package]]
name = "ohos-deviceinfo"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e75dc6477dd4a8bafe2e7b1feb9cf10e882d3b15903e51f320a80015a59d93"
dependencies = [
"ohos-deviceinfo-sys",
]
[[package]]
name = "ohos-deviceinfo-sys"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e847d268f96c5ad9d03fd6bd303f9529ab3a83019497fa1c1a585aac50c378ec"
[[package]]
name = "ohos-drawing-sys"
version = "0.2.2"
@ -5437,6 +5461,15 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93e60dacb893ed4eb57e8fd9eff81b8ad0153842661b3093927bdfd861506652"
[[package]]
name = "ohos-window-manager-sys"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f0b36f3adea9bae4251f2c215e5569330a59b1a150d73af3182fe92fb490570"
dependencies = [
"ohos-sys-opaque-types",
]
[[package]]
name = "once_cell"
version = "1.21.3"
@ -7086,9 +7119,12 @@ dependencies = [
"nix",
"objc2-app-kit 0.3.1",
"objc2-foundation 0.3.1",
"ohos-abilitykit-sys",
"ohos-deviceinfo",
"ohos-ime",
"ohos-ime-sys",
"ohos-vsync",
"ohos-window-manager-sys",
"raw-window-handle",
"rustls",
"serde_json",

View file

@ -85,15 +85,17 @@ backtrace = { workspace = true }
env_filter = "0.1.3"
euclid = { workspace = true }
hilog = "0.2.0"
# force inprocess, until libc-rs 0.2.156 is released containing
# https://github.com/rust-lang/libc/commit/9e248e212c5602cb4e98676e4c21ea0382663a12
# force inprocess until we add multi-process support for ohos
ipc-channel = { workspace = true, features = ["force-inprocess"] }
napi-derive-ohos = "1.0.4"
napi-ohos = "1.0.4"
ohos-ime = "0.4.0"
ohos-ime-sys = "0.2.0"
ohos-deviceinfo = "0.1.0"
ohos-abilitykit-sys = { version = "0.1.0", features = ["api-14"] }
ohos-vsync = "0.1.3"
xcomponent-sys = { version = "0.3.1", features = ["api-12", "keyboard-types"] }
ohos-window-manager-sys = { version = "0.1", features = ["api-14"] }
xcomponent-sys = { version = "0.3.1", features = ["api-14", "keyboard-types"] }
[target.'cfg(any(target_os = "android", target_env = "ohos"))'.dependencies]
nix = { workspace = true, features = ["fs"] }

View file

@ -45,12 +45,8 @@ mod simpleservo;
#[derive(Debug)]
pub struct InitOpts {
pub url: String,
pub device_type: String,
pub os_full_name: String,
/// Path to application data bundled with the servo app, e.g. web-pages.
pub resource_dir: String,
pub cache_dir: String,
pub display_density: f64,
pub commandline_args: String,
}
@ -626,10 +622,6 @@ pub fn register_prompt_toast_callback(callback: Function<String, ()>) -> napi_oh
#[napi]
pub fn init_servo(init_opts: InitOpts) -> napi_ohos::Result<()> {
info!("Servo is being initialised with the following Options: ");
info!(
"Device Type: {}, DisplayDensity: {}",
init_opts.device_type, init_opts.display_density
);
info!("Initial URL: {}", init_opts.url);
let channel = if let Some(channel) = SERVO_CHANNEL.get() {
channel

View file

@ -2,6 +2,7 @@
* 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::cell::RefCell;
use std::ffi::{CString, c_char};
use std::fs;
use std::os::raw::c_void;
use std::path::PathBuf;
@ -9,7 +10,9 @@ use std::ptr::NonNull;
use std::rc::Rc;
use dpi::PhysicalSize;
use log::{debug, info, warn};
use log::{debug, error, info, warn};
use ohos_abilitykit_sys::runtime::application_context;
use ohos_window_manager_sys::display_manager;
use raw_window_handle::{
DisplayHandle, OhosDisplayHandle, OhosNdkWindowHandle, RawDisplayHandle, RawWindowHandle,
WindowHandle,
@ -23,6 +26,46 @@ use crate::egl::ohos::InitOpts;
use crate::egl::ohos::resources::ResourceReaderInstance;
use crate::prefs::{ArgumentParsingResult, parse_command_line_arguments};
#[derive(Debug)]
struct NativeValues {
cache_dir: String,
display_density: f32,
device_type: ohos_deviceinfo::OhosDeviceType,
os_full_name: String,
}
/// Gets the resource and cache directory from the native c methods.
fn get_native_values() -> NativeValues {
let cache_dir = {
const BUFFER_SIZE: i32 = 100;
let mut buffer: Vec<u8> = Vec::with_capacity(BUFFER_SIZE as usize);
let mut write_length = 0;
unsafe {
application_context::OH_AbilityRuntime_ApplicationContextGetCacheDir(
buffer.as_mut_ptr().cast(),
BUFFER_SIZE,
&mut write_length,
)
.expect("Call to cache dir failed");
buffer.set_len(write_length as usize);
String::from_utf8(buffer).expect("UTF-8")
}
};
let display_density = unsafe {
let mut density: f32 = 0_f32;
display_manager::OH_NativeDisplayManager_GetDefaultDisplayDensityPixels(&mut density)
.expect("Could not get displaydensity");
density
};
NativeValues {
cache_dir,
display_density,
device_type: ohos_deviceinfo::get_device_type(),
os_full_name: String::from(ohos_deviceinfo::get_os_full_name().unwrap_or("Undefined")),
}
}
/// Initialize Servo. At that point, we need a valid GL context.
/// In the future, this will be done in multiple steps.
pub fn init(
@ -34,6 +77,12 @@ pub fn init(
) -> Result<Rc<RunningAppState>, &'static str> {
info!("Entered simpleservo init function");
crate::init_crypto();
let native_values = get_native_values();
info!("Device Type {:?}", native_values.device_type);
info!("OS Full Name {:?}", native_values.os_full_name);
info!("ResourceDir {:?}", options.resource_dir);
let resource_dir = PathBuf::from(&options.resource_dir).join("servo");
debug!("Resources are located at: {:?}", resource_dir);
resources::set(Box::new(ResourceReaderInstance::new(resource_dir.clone())));
@ -49,7 +98,7 @@ pub fn init(
);
debug!("Servo commandline args: {:?}", args);
let config_dir = PathBuf::from(&options.cache_dir).join("servo");
let config_dir = PathBuf::from(&native_values.cache_dir).join("servo");
debug!("Configs are located at: {:?}", config_dir);
let _ = crate::prefs::DEFAULT_CONFIG_DIR
.set(config_dir.clone())
@ -133,7 +182,7 @@ pub fn init(
let app_state = RunningAppState::new(
Some(options.url),
options.display_density as f32,
native_values.display_density as f32,
rendering_context,
servo,
window_callbacks,

View file

@ -293,8 +293,8 @@ class OpenHarmonyTarget(CrossBuildTarget):
meta = json.load(meta_file)
ohos_api_version = int(meta["apiVersion"])
ohos_sdk_version = parse_version(meta["version"])
if ohos_sdk_version < parse_version("5.0") or ohos_api_version < 12:
raise RuntimeError("Building servo for OpenHarmony requires SDK version 5.0 (API-12) or newer.")
if ohos_sdk_version < parse_version("5.0") or ohos_api_version < 14:
raise RuntimeError("Building servo for OpenHarmony requires SDK version 5.0.2 (API-14) or newer.")
print(f"Info: The OpenHarmony SDK {ohos_sdk_version} is targeting API-level {ohos_api_version}")
except (OSError, json.JSONDecodeError) as e:
print(f"Failed to read metadata information from {package_info}")

View file

@ -15,35 +15,10 @@ interface ServoXComponentInterface {
interface InitOpts {
url: string;
deviceType: string,
osFullName: string,
resourceDir: string,
cacheDir: string,
displayDensity: number,
commandlineArgs: string,
}
function get_density(): number {
try {
let displayClass = display.getDefaultDisplaySync();
console.info('Test densityDPI:' + JSON.stringify(displayClass.densityDPI));
return displayClass.densityDPI / 160;
} catch (exception) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception));
return 3;
}
}
function get_device_type(): string {
let device_type: string = deviceInfo.deviceType;
if (device_type == "") {
console.error("deviceInfo.deviceType is empty string!")
} else {
console.info("Device type is " + device_type)
}
return device_type;
}
function prompt_toast(msg: string) {
promptAction.showToast({
message: msg,
@ -114,16 +89,10 @@ struct Index {
.onLoad((xComponentContext) => {
this.xComponentContext = xComponentContext as ServoXComponentInterface;
let resource_dir: string = this.context.resourceDir;
let cache_dir: string = this.context.cacheDir;
console.debug("resourceDir: ", resource_dir);
console.debug("cacheDir: ", cache_dir);
let init_options: InitOpts = {
url: this.urlToLoad,
deviceType: get_device_type(),
osFullName: deviceInfo.osFullName,
displayDensity: get_density(),
resourceDir: resource_dir,
cacheDir: cache_dir,
commandlineArgs: this.CommandlineArgs
}
this.xComponentContext.initServo(init_options)