Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ ohos-xcomponent-binding = { version = "0.2" }
ohos-ime-binding = { version = "0.1" }
ohos-web-binding = { version = "0.1" }
ohos-display-binding = { version = "0.0.1" }
ohos-resource-manager-binding = { version = "0.2" }

http = { version = "1.1" }
http = { version = "1.1" }
1 change: 1 addition & 0 deletions crates/ability/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ ohos-arkui-binding = { workspace = true, features = ["napi"] }
ohos-xcomponent-binding = { workspace = true }
ohos-ime-binding = { workspace = true }
ohos-display-binding = { workspace = true }
ohos-resource-manager-binding = { workspace = true }

# for webview feature
ohos-web-binding = { workspace = true, optional = true }
Expand Down
4 changes: 2 additions & 2 deletions crates/ability/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ openharmony-ability is the Rust runtime crate in this repository. It provides li

## Runtime Context

`NativeAbility` passes the ArkTS init context into native code during `init(context)`. In the Rust runtime, `OpenHarmonyApp` can read `moduleName`, `basePath`, `prefPath`, and `preferredLocales` via `init_context()`, `module_name()`, `base_path()`, `pref_path()`, and `preferred_locales()`.
`NativeAbility` passes the ArkTS init context into native code during `init(context)`. In the Rust runtime, `OpenHarmonyApp` can read `moduleName`, `basePath`, `prefPath`, and `preferredLocales` via `init_context()`, `module_name()`, `base_path()`, `pref_path()`, and `preferred_locales()`. The Harmony `resourceManager` instance is also initialized during `init(context)` and can be accessed through `resource_manager()`.

## License

This project is licensed under the [MIT license](https://github.com/harmony-contrib/openharmony-ability/blob/main/LICENSE)
This project is licensed under the [MIT license](https://github.com/harmony-contrib/openharmony-ability/blob/main/LICENSE)
40 changes: 39 additions & 1 deletion crates/ability/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ use ohos_xcomponent_binding::RawWindow;
use crate::{
get_helper, get_main_thread_env, get_permission_request_tsfn, unknown_to_permission_promise,
AbilityError, AvoidArea, AvoidAreaType, Configuration, Event, OpenHarmonyWaker,
PermissionRequest, PermissionRequestCode, PermissionRequestOutput, Rect, WAKER,
PermissionRequest, PermissionRequestCode, PermissionRequestOutput, Rect, ResourceManager,
WAKER,
};

static ID: AtomicI64 = AtomicI64::new(0);
Expand Down Expand Up @@ -75,6 +76,21 @@ pub struct AbilityInitContext {
pub module_name: Option<String>,
}

impl AbilityInitContext {
pub fn from_object(context: Option<&Object<'_>>) -> Result<Self> {
let Some(context) = context else {
return Ok(Self::default());
};

Ok(Self {
base_path: context.get("basePath")?,
pref_path: context.get("prefPath")?,
preferred_locales: context.get("preferredLocales")?,
module_name: context.get("moduleName")?,
})
}
}

#[derive(Clone)]
pub struct OpenHarmonyAppInner {
pub(crate) raw_window: Option<RawWindow>,
Expand All @@ -88,6 +104,7 @@ pub struct OpenHarmonyAppInner {
pub(crate) window_rect: Rect,
pub(crate) avoid_areas: HashMap<AvoidAreaType, AvoidArea>,
pub(crate) init_context: AbilityInitContext,
pub(crate) resource_manager: Option<ResourceManager>,
}

impl PartialEq for OpenHarmonyAppInner {
Expand Down Expand Up @@ -144,6 +161,7 @@ impl OpenHarmonyAppInner {
window_rect: Default::default(),
avoid_areas: HashMap::new(),
init_context: AbilityInitContext::default(),
resource_manager: None,
}
}

Expand Down Expand Up @@ -211,6 +229,14 @@ impl OpenHarmonyAppInner {
self.init_context = context;
}

pub fn resource_manager(&self) -> Option<ResourceManager> {
self.resource_manager.clone()
}

pub fn set_resource_manager(&mut self, resource_manager: Option<ResourceManager>) {
self.resource_manager = resource_manager;
}

pub fn exit(&self, code: i32) -> Result<()> {
let ret = unsafe { get_helper() };
if let Some(h) = ret.borrow().as_ref() {
Expand Down Expand Up @@ -332,6 +358,18 @@ impl OpenHarmonyApp {
self.init_context().preferred_locales
}

pub fn resource_manager(&self) -> Option<ResourceManager> {
self.inner.read().unwrap().resource_manager()
}

#[doc(hidden)]
pub fn set_resource_manager(&self, resource_manager: Option<ResourceManager>) {
self.inner
.write()
.unwrap()
.set_resource_manager(resource_manager);
}

pub fn show_keyboard(&self) {
let _guard = self
.is_keyboard_show
Expand Down
2 changes: 2 additions & 0 deletions crates/ability/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod input;
mod lifecycle;
mod memory;
mod render;
mod resource;
mod stage;
mod waker;

Expand All @@ -26,6 +27,7 @@ pub use input::*;
pub use lifecycle::*;
pub use memory::*;
pub use render::*;
pub use resource::*;
pub use stage::*;
pub use waker::*;

Expand Down
37 changes: 37 additions & 0 deletions crates/ability/src/resource.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::{ops::Deref, sync::Arc};

use napi_ohos::{bindgen_prelude::Object, Env, Result};
use ohos_resource_manager_binding::ResourceManager as NativeResourceManager;
pub use ohos_resource_manager_binding::ScreenDensity as ResourceScreenDensity;
pub use ohos_resource_manager_binding::{IconType, RawDir, RawFile, RawFile64, RawFileError};

#[derive(Clone)]
pub struct ResourceManager(Arc<NativeResourceManager>);

impl ResourceManager {
pub fn new(env: Env, resource_manager: Object) -> Self {
Self(Arc::new(NativeResourceManager::new(env, resource_manager)))
}

pub fn from_init_context(env: Env, context: Option<&Object<'_>>) -> Result<Option<Self>> {
let Some(context) = context else {
return Ok(None);
};

Ok(context
.get::<Object>("resourceManager")?
.map(|resource_manager| Self::new(env, resource_manager)))
}

pub fn inner(&self) -> &NativeResourceManager {
self.0.as_ref()
}
}

impl Deref for ResourceManager {
type Target = NativeResourceManager;

fn deref(&self) -> &Self::Target {
self.inner()
}
}
4 changes: 2 additions & 2 deletions crates/derive/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ fn openharmony_app(app: OpenHarmonyApp) {

### Init Context

The generated `init(context)` forwards ArkTS init data into native code. In the Rust runtime, you can read it through `app.init_context()`, `app.module_name()`, `app.base_path()`, `app.pref_path()`, and `app.preferred_locales()`.
The generated `init(context)` forwards ArkTS init data into native code. In the Rust runtime, you can read it through `app.init_context()`, `app.module_name()`, `app.base_path()`, `app.pref_path()`, and `app.preferred_locales()`. The Harmony `resourceManager` instance is initialized alongside the other init data and is available through `app.resource_manager()`.

### webview

Expand Down Expand Up @@ -96,4 +96,4 @@ fn openharmony_app(app: OpenHarmonyApp) {
}
});
}
```
```
8 changes: 6 additions & 2 deletions crates/derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,13 @@ pub fn ability(attr: TokenStream, item: TokenStream) -> TokenStream {
#[napi_derive_ohos::napi]
pub fn init<'a>(
env: &'a napi_ohos::Env,
context: Option<openharmony_ability::AbilityInitContext>,
#[napi(ts_arg_type = "AbilityInitContext")]
context: Option<napi_ohos::bindgen_prelude::Object<'a>>,
) -> napi_ohos::Result<openharmony_ability::ApplicationLifecycle<'a>> {
(*APP).set_init_context(context.unwrap_or_default());
let init_context = openharmony_ability::AbilityInitContext::from_object(context.as_ref())?;
let resource_manager = openharmony_ability::ResourceManager::from_init_context(*env, context.as_ref())?;
(*APP).set_init_context(init_context);
(*APP).set_resource_manager(resource_manager);
let lifecycle_handle = openharmony_ability::create_lifecycle_handle(env, (*APP).clone())?;
#fn_name((*APP).clone());
Ok(lifecycle_handle)
Expand Down
1 change: 1 addition & 0 deletions native_ability/src/main/ets/ability/NativeAbility.ets
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export class NativeAbility extends UIAbility {
prefPath: context?.filesDir ?? "",
preferredLocales: context?.config?.language ?? "",
moduleName,
resourceManager: context?.resourceManager,
};
}

Expand Down
2 changes: 2 additions & 0 deletions native_ability/src/main/ets/ability/type.ets
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NodeContent } from "@kit.ArkUI";
import resourceManager from "@ohos.resourceManager";

export interface ApplicationLifecycle {
environmentCallback: EnvironmentCallback;
Expand Down Expand Up @@ -66,6 +67,7 @@ export interface AbilityInitContext {
prefPath?: string;
preferredLocales?: string;
moduleName?: string;
resourceManager?: resourceManager.ResourceManager;
}

export interface Module {
Expand Down
15 changes: 9 additions & 6 deletions native_ability/src/main/ets/webview/DefaultWebview.ets
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,15 @@ export class RustWebviewNodeController extends NodeController {
return getCookies(url) as string;
};
const loadUrl = (url: string, header?: Record<string, string>) => {
const headers = Object.keys((header || {}) as Record<string, string>).reduce((t, i) => {
if (!!header![i]) {
t.push({ headerKey: i, headerValue: header![i] });
}
return t;
}, [] as Array<WebHeader>);
const headers = Object.keys((header || {}) as Record<string, string>).reduce(
(t, i) => {
if (!!header![i]) {
t.push({ headerKey: i, headerValue: header![i] });
}
return t;
},
[] as Array<WebHeader>,
);
controller.loadUrl(url, headers);
};

Expand Down
4 changes: 4 additions & 0 deletions package/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 0.4.0-beta.5
- Add ResourceManager when init

---
# 0.4.0-beta.4
- Fix onBackPress trigger logic

Expand Down
2 changes: 1 addition & 1 deletion package/oh-package.json5
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"name": "@ohos-rs/ability",
"description": "Adaptor for OpenHarmony/HarmonyNext native abilities",
"main": "index.ets",
"version": "0.4.0-beta.4",
"version": "0.4.0-beta.5",
"repository": "https://github.com/harmony-contrib/openharmony-ability.git",
"dependencies": {},
"keywords": [
Expand Down
Loading