Fix various clippy warnings on OpenHarmony (#34281)

* ohos: Fix more clippy warnings

Signed-off-by: Jonathan Schwender <jonathan.schwender@huawei.com>
Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>

* Remove unnecessary `macro_use`

We can use `use` instead. Removes a warning about
unused macro_use on OpenHarmony.

Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>

---------

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-11-19 06:21:48 +01:00 committed by GitHub
parent caf2467649
commit 09684a3501
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 37 additions and 51 deletions

View file

@ -22,16 +22,16 @@ use crate::{
FontTemplateDescriptor, LocalFontIdentifier, LowercaseFontFamilyName, FontTemplateDescriptor, LocalFontIdentifier, LowercaseFontFamilyName,
}; };
static FONT_LIST: LazyLock<FontList> = LazyLock::new(|| FontList::new()); static FONT_LIST: LazyLock<FontList> = LazyLock::new(FontList::new);
/// When testing the ohos font code on linux, we can pass the fonts directory of the SDK /// When testing the ohos font code on linux, we can pass the fonts directory of the SDK
/// via an environment variable. /// via an environment variable.
#[cfg(ohos_mock)] #[cfg(ohos_mock)]
static OHOS_FONTS_DIR: &'static str = env!("OHOS_SDK_FONTS_DIR"); static OHOS_FONTS_DIR: &str = env!("OHOS_SDK_FONTS_DIR");
/// On OpenHarmony devices the fonts are always located here. /// On OpenHarmony devices the fonts are always located here.
#[cfg(not(ohos_mock))] #[cfg(not(ohos_mock))]
static OHOS_FONTS_DIR: &'static str = "/system/fonts"; static OHOS_FONTS_DIR: &str = "/system/fonts";
#[allow(unused)] #[allow(unused)]
#[derive(Clone, Copy, Debug, Default)] #[derive(Clone, Copy, Debug, Default)]
@ -80,15 +80,13 @@ struct FontList {
fn enumerate_font_files() -> io::Result<Vec<PathBuf>> { fn enumerate_font_files() -> io::Result<Vec<PathBuf>> {
let mut font_list = vec![]; let mut font_list = vec![];
for elem in fs::read_dir(OHOS_FONTS_DIR)? { for elem in fs::read_dir(OHOS_FONTS_DIR)?.flatten() {
if let Ok(e) = elem { if elem.file_type().unwrap().is_file() {
if e.file_type().unwrap().is_file() { let name = elem.file_name();
let name = e.file_name(); let raw_name = name.as_bytes();
let raw_name = name.as_bytes(); if raw_name.ends_with(b".ttf".as_ref()) || raw_name.ends_with(b".ttc".as_ref()) {
if raw_name.ends_with(b".ttf".as_ref()) || raw_name.ends_with(b".ttc".as_ref()) { debug!("Found font {}", elem.file_name().to_str().unwrap());
debug!("Found font {}", e.file_name().to_str().unwrap()); font_list.push(elem.path())
font_list.push(e.path())
}
} }
} }
} }
@ -176,7 +174,7 @@ fn split_noto_font_name(name: &str) -> Vec<String> {
} }
} }
} }
if current_word.len() > 0 { if !current_word.is_empty() {
name_components.push(current_word); name_components.push(current_word);
} }
name_components name_components
@ -291,11 +289,10 @@ fn parse_font_filenames(font_files: Vec<PathBuf>) -> Vec<FontFamily> {
} }
} }
let families = families families
.into_iter() .into_iter()
.map(|(name, fonts)| FontFamily { name, fonts }) .map(|(name, fonts)| FontFamily { name, fonts })
.collect(); .collect()
families
} }
impl FontList { impl FontList {
@ -310,7 +307,7 @@ impl FontList {
fn detect_installed_font_families() -> Vec<FontFamily> { fn detect_installed_font_families() -> Vec<FontFamily> {
let mut families = enumerate_font_files() let mut families = enumerate_font_files()
.inspect_err(|e| error!("Failed to enumerate font files due to `{e:?}`")) .inspect_err(|e| error!("Failed to enumerate font files due to `{e:?}`"))
.and_then(|font_files| Ok(parse_font_filenames(font_files))) .map(|font_files| parse_font_filenames(font_files))
.unwrap_or_else(|_| FontList::fallback_font_families()); .unwrap_or_else(|_| FontList::fallback_font_families());
families.extend(Self::hardcoded_font_families()); families.extend(Self::hardcoded_font_families());
families families
@ -325,14 +322,14 @@ impl FontList {
FontFamily { FontFamily {
name: "HMOS Color Emoji".to_string(), name: "HMOS Color Emoji".to_string(),
fonts: vec![Font { fonts: vec![Font {
filepath: FontList::font_absolute_path("HMOSColorEmojiCompat.ttf".into()), filepath: FontList::font_absolute_path("HMOSColorEmojiCompat.ttf"),
..Default::default() ..Default::default()
}], }],
}, },
FontFamily { FontFamily {
name: "HMOS Color Emoji Flags".to_string(), name: "HMOS Color Emoji Flags".to_string(),
fonts: vec![Font { fonts: vec![Font {
filepath: FontList::font_absolute_path("HMOSColorEmojiFlags.ttf".into()), filepath: FontList::font_absolute_path("HMOSColorEmojiFlags.ttf"),
..Default::default() ..Default::default()
}], }],
}, },

View file

@ -128,7 +128,7 @@ winit = "0.30.5"
[target.'cfg(any(all(target_os = "linux", not(target_env = "ohos")), target_os = "windows"))'.dependencies] [target.'cfg(any(all(target_os = "linux", not(target_env = "ohos")), target_os = "windows"))'.dependencies]
image = { workspace = true } image = { workspace = true }
[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies] [target.'cfg(any(all(target_os = "linux", not(target_env = "ohos")), target_os = "macos"))'.dependencies]
sig = "1.0" sig = "1.0"
[target.'cfg(target_os = "windows")'.dependencies] [target.'cfg(target_os = "windows")'.dependencies]

View file

@ -11,6 +11,8 @@ pub fn install() {
use std::sync::atomic; use std::sync::atomic;
use std::thread; use std::thread;
use sig::signal;
use crate::backtrace; use crate::backtrace;
extern "C" fn handler(sig: i32) { extern "C" fn handler(sig: i32) {

View file

@ -30,7 +30,6 @@ use ohos_sys::xcomponent::{
use servo::compositing::windowing::EmbedderEvent; use servo::compositing::windowing::EmbedderEvent;
use servo::embedder_traits; use servo::embedder_traits;
use servo::embedder_traits::{InputMethodType, PromptResult}; use servo::embedder_traits::{InputMethodType, PromptResult};
use servo::euclid::Point2D;
use servo::style::Zero; use servo::style::Zero;
use simpleservo::EventLoopWaker; use simpleservo::EventLoopWaker;
use xcomponent_sys::{ use xcomponent_sys::{
@ -82,7 +81,7 @@ unsafe impl Send for XComponentWrapper {}
unsafe impl Send for WindowWrapper {} unsafe impl Send for WindowWrapper {}
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
enum TouchEventType { pub(super) enum TouchEventType {
Down, Down,
Up, Up,
Move, Move,
@ -91,7 +90,7 @@ enum TouchEventType {
} }
#[derive(Debug)] #[derive(Debug)]
enum ServoAction { pub(super) enum ServoAction {
WakeUp, WakeUp,
LoadUrl(String), LoadUrl(String),
GoBack, GoBack,
@ -206,11 +205,9 @@ unsafe extern "C" fn on_vsync_cb(
data: *mut ::core::ffi::c_void, data: *mut ::core::ffi::c_void,
) { ) {
trace!("Vsync callback at time {timestamp}"); trace!("Vsync callback at time {timestamp}");
// SAFETY: We require the function registering us as a callback // SAFETY: We require the function registering us as a callback provides a valid
let (native_vsync, data) = unsafe { // `OH_NativeVSync` object. We do not use `data` after this point.
let native = ohos_vsync::NativeVsync::from_raw(data.cast()); let native_vsync = unsafe { ohos_vsync::NativeVsync::from_raw(data.cast()) };
(native, 0)
};
call(ServoAction::Vsync).unwrap(); call(ServoAction::Vsync).unwrap();
// Todo: Do we have a callback for when the frame finished rendering? // Todo: Do we have a callback for when the frame finished rendering?
unsafe { unsafe {
@ -507,7 +504,7 @@ pub fn go_forward() {
#[napi(js_name = "registerURLcallback")] #[napi(js_name = "registerURLcallback")]
pub fn register_url_callback(callback: Function<String, ()>) -> napi_ohos::Result<()> { pub fn register_url_callback(callback: Function<String, ()>) -> napi_ohos::Result<()> {
debug!("register_url_callback called!"); debug!("register_url_callback called!");
let mut tsfn_builder = callback.build_threadsafe_function(); let tsfn_builder = callback.build_threadsafe_function();
let function = tsfn_builder let function = tsfn_builder
.max_queue_size::<UPDATE_URL_QUEUE_SIZE>() .max_queue_size::<UPDATE_URL_QUEUE_SIZE>()
.build()?; .build()?;
@ -522,7 +519,7 @@ pub fn register_url_callback(callback: Function<String, ()>) -> napi_ohos::Resul
#[napi] #[napi]
pub fn register_prompt_toast_callback(callback: Function<String, ()>) -> napi_ohos::Result<()> { pub fn register_prompt_toast_callback(callback: Function<String, ()>) -> napi_ohos::Result<()> {
debug!("register_prompt_toast_callback called!"); debug!("register_prompt_toast_callback called!");
let mut tsfn_builder = callback.build_threadsafe_function(); let tsfn_builder = callback.build_threadsafe_function();
let function = tsfn_builder.max_queue_size::<PROMPT_QUEUE_SIZE>().build()?; let function = tsfn_builder.max_queue_size::<PROMPT_QUEUE_SIZE>().build()?;
PROMPT_TOAST PROMPT_TOAST

View file

@ -82,18 +82,12 @@ pub fn init(
"--prefs-file /path/to/prefs.json", "--prefs-file /path/to/prefs.json",
); );
let opts_matches; let opts_matches = match opts::from_cmdline_args(opts, &args) {
let content_process_token; ArgumentParsingResult::ContentProcess(matches, _token) => {
match opts::from_cmdline_args(opts, &args) {
ArgumentParsingResult::ContentProcess(matches, token) => {
error!("Content Process mode not supported / tested yet on OpenHarmony!"); error!("Content Process mode not supported / tested yet on OpenHarmony!");
opts_matches = matches; matches
content_process_token = Some(token);
},
ArgumentParsingResult::ChromeProcess(matches) => {
opts_matches = matches;
content_process_token = None;
}, },
ArgumentParsingResult::ChromeProcess(matches) => matches,
}; };
crate::prefs::register_user_prefs(&opts_matches); crate::prefs::register_user_prefs(&opts_matches);

View file

@ -26,7 +26,6 @@ use servo::script_traits::{
}; };
use servo::servo_geometry::DeviceIndependentPixel; use servo::servo_geometry::DeviceIndependentPixel;
use servo::style_traits::DevicePixel; use servo::style_traits::DevicePixel;
use servo::webrender_api::units::DeviceIntRect;
use servo::webrender_api::ScrollLocation; use servo::webrender_api::ScrollLocation;
use servo::webrender_traits::RenderingContext; use servo::webrender_traits::RenderingContext;
use servo::{gl, Servo, TopLevelBrowsingContextId}; use servo::{gl, Servo, TopLevelBrowsingContextId};
@ -501,7 +500,8 @@ impl ServoGlue {
let trusted = origin == PromptOrigin::Trusted; let trusted = origin == PromptOrigin::Trusted;
let res = match definition { let res = match definition {
PromptDefinition::Alert(message, sender) => { PromptDefinition::Alert(message, sender) => {
sender.send(cb.prompt_alert(message, trusted)) cb.prompt_alert(message, trusted);
sender.send(())
}, },
PromptDefinition::OkCancel(message, sender) => { PromptDefinition::OkCancel(message, sender) => {
sender.send(cb.prompt_ok_cancel(message, trusted)) sender.send(cb.prompt_ok_cancel(message, trusted))

View file

@ -4,21 +4,18 @@
use cfg_if::cfg_if; use cfg_if::cfg_if;
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[macro_use]
extern crate sig;
#[cfg(test)] #[cfg(test)]
mod test; mod test;
#[cfg(not(target_os = "android"))] #[cfg(not(target_os = "android"))]
mod backtrace; mod backtrace;
#[cfg(not(target_env = "ohos"))]
mod crash_handler; mod crash_handler;
#[cfg(not(any(target_os = "android", target_env = "ohos")))] #[cfg(not(any(target_os = "android", target_env = "ohos")))]
pub(crate) mod desktop; pub(crate) mod desktop;
#[cfg(any(target_os = "android", target_env = "ohos"))] #[cfg(any(target_os = "android", target_env = "ohos"))]
mod egl; mod egl;
#[cfg(not(target_os = "android"))] #[cfg(not(any(target_os = "android", target_env = "ohos")))]
mod panic_hook; mod panic_hook;
mod parser; mod parser;
mod prefs; mod prefs;

View file

@ -2,20 +2,19 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[cfg(not(any(target_os = "android", target_env = "ohos")))]
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use log::warn;
use servo::net_traits::pub_domains::is_reg_domain; use servo::net_traits::pub_domains::is_reg_domain;
use servo::servo_config::pref; use servo::servo_config::pref;
use servo::servo_url::ServoUrl; use servo::servo_url::ServoUrl;
use url::{self, Url};
#[cfg(not(any(target_os = "android", target_env = "ohos")))] #[cfg(not(any(target_os = "android", target_env = "ohos")))]
pub fn parse_url_or_filename(cwd: &Path, input: &str) -> Result<ServoUrl, ()> { pub fn parse_url_or_filename(cwd: &Path, input: &str) -> Result<ServoUrl, ()> {
match ServoUrl::parse(input) { match ServoUrl::parse(input) {
Ok(url) => Ok(url), Ok(url) => Ok(url),
Err(url::ParseError::RelativeUrlWithoutBase) => { Err(url::ParseError::RelativeUrlWithoutBase) => {
Url::from_file_path(&*cwd.join(input)).map(ServoUrl::from_url) url::Url::from_file_path(&*cwd.join(input)).map(ServoUrl::from_url)
}, },
Err(_) => Err(()), Err(_) => Err(()),
} }
@ -33,7 +32,7 @@ pub fn get_default_url(
let cmdline_url = url_opt.map(|s| s.to_string()).and_then(|url_string| { let cmdline_url = url_opt.map(|s| s.to_string()).and_then(|url_string| {
parse_url_or_filename(cwd.as_ref(), &url_string) parse_url_or_filename(cwd.as_ref(), &url_string)
.map_err(|error| { .map_err(|error| {
warn!("URL parsing failed ({:?}).", error); log::warn!("URL parsing failed ({:?}).", error);
error error
}) })
.ok() .ok()