mod host_config;
use std::ffi::{CStr, CString, c_char, c_void};
use std::sync::{Mutex, OnceLock};
use euv::{
App, DamageRegion, DeviceMotionSample, HarmonyAvoidArea, HarmonyDeviceType, HarmonyFoldState,
HarmonyHostCommand, HarmonyLifecycleHook, HarmonyPlatform, HarmonyWindowMode, Modifiers,
NativeSystemFont, NetworkStatus, PlatformBackend, PlatformKind, RenderMode, SystemEvent,
ThemeMode, WindowConfig, WindowEvent, WindowId, harmony_cursor_to_pointer_style,
register_native_action_bridge, reset_reactive_runtime,
};
use euv_example::{ShowcaseState, create_showcase_app_for_platform};
static HARMONY_ACTIONS: OnceLock<Mutex<Vec<(String, String, String)>>> = OnceLock::new();
fn harmony_native_action_bridge(kind: &str, arg1: &str, arg2: &str) -> bool {
let queue: &Mutex<Vec<(String, String, String)>> =
HARMONY_ACTIONS.get_or_init(|| Mutex::new(Vec::new()));
if let Ok(mut guard) = queue.lock() {
guard.push((kind.to_string(), arg1.to_string(), arg2.to_string()));
return true;
}
false
}
pub struct EuvHarmonyHost {
app: App,
_state: ShowcaseState,
platform: HarmonyPlatform,
wid: WindowId,
native_window: usize,
last_commands_cstr: CString,
}
fn cstr_or_empty(ptr: *const c_char) -> String {
if ptr.is_null() {
return String::new();
}
unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() }
}
fn escape_json(input: &str) -> String {
let mut out: String = String::with_capacity(input.len() + 4);
for ch in input.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
other => out.push(other),
}
}
out
}
fn drain_platform_events(host: &mut EuvHarmonyHost) {
let events: Vec<WindowEvent> = host.platform.poll_events();
for ev in events {
host.app.dispatch_window_event(ev);
}
}
#[unsafe(no_mangle)]
pub extern "C" fn euv_harmony_host_create(
device_type: *const c_char,
phys_width: u32,
phys_height: u32,
density: f32,
) -> *mut EuvHarmonyHost {
register_native_action_bridge(harmony_native_action_bridge);
reset_reactive_runtime();
let requested: String = cstr_or_empty(device_type);
let device: HarmonyDeviceType =
HarmonyDeviceType::from_str_id(&requested).unwrap_or(host_config::HOST_HARMONY_DEVICE);
let mut platform: HarmonyPlatform = HarmonyPlatform::for_device_type(device);
let d: f32 = density.clamp(0.75, 4.5);
let lw: u32 = ((phys_width.max(1) as f32) / d).round().max(1.0) as u32;
let lh: u32 = ((phys_height.max(1) as f32) / d).round().max(1.0) as u32;
let mut cfg: WindowConfig = WindowConfig::default();
cfg.set_size(lw, lh);
let Ok(win_state) = platform.create_window(&cfg) else {
return std::ptr::null_mut();
};
let wid: WindowId = win_state.get_id();
let Ok((mut app, state)) =
create_showcase_app_for_platform(PlatformKind::HarmonyOs, RenderMode::Software)
else {
return std::ptr::null_mut();
};
app.get_mut_renderer()
.get_mut_software()
.set_font_provider(NativeSystemFont::system());
app.set_exact_physical_viewport(phys_width.max(1), phys_height.max(1), d);
let boxed: Box<EuvHarmonyHost> = Box::new(EuvHarmonyHost {
app,
_state: state,
platform,
wid,
native_window: 0,
last_commands_cstr: CString::new("[]").unwrap_or_default(),
});
Box::into_raw(boxed)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_destroy(ptr: *mut EuvHarmonyHost) {
if ptr.is_null() {
return;
}
let mut host: Box<EuvHarmonyHost> = unsafe { Box::from_raw(ptr) };
let _ = host.platform.handle_lifecycle_hook(HarmonyLifecycleHook::OnDestroy);
drain_platform_events(&mut host);
drop(host);
reset_reactive_runtime();
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_attach_surface(
ptr: *mut EuvHarmonyHost,
native_window: *mut c_void,
xcomponent: *mut c_void,
phys_width: u32,
phys_height: u32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
host.native_window = native_window as usize;
host.platform.attach_xcomponent(
native_window as usize,
xcomponent as usize,
phys_width.max(1),
phys_height.max(1),
);
let d: f32 = host.platform.get_profile().get_density().clamp(0.75, 4.5);
if phys_width > 0 && phys_height > 0 {
host.app.set_exact_physical_viewport(phys_width, phys_height, d);
}
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_detach_surface(ptr: *mut EuvHarmonyHost) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
host.native_window = 0;
host.platform.detach_xcomponent();
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_lifecycle(
ptr: *mut EuvHarmonyHost,
hook_tag: i32,
payload: *const c_char,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let text: String = cstr_or_empty(payload);
let hook: HarmonyLifecycleHook = match hook_tag {
1 => HarmonyLifecycleHook::OnCreate {
want_uri: if text.is_empty() { None } else { Some(text) },
},
2 => HarmonyLifecycleHook::OnForeground,
3 => HarmonyLifecycleHook::OnWindowActive,
4 => HarmonyLifecycleHook::OnWindowInactive,
5 => HarmonyLifecycleHook::OnBackground,
6 => HarmonyLifecycleHook::OnWindowStageDestroy,
7 => HarmonyLifecycleHook::OnDestroy,
8 => HarmonyLifecycleHook::OnBackPress,
9 => HarmonyLifecycleHook::OnNewWant(text),
_ => return,
};
let cancel_pointers: bool = matches!(hook_tag, 4 | 5 | 6);
let _ = host.platform.handle_lifecycle_hook(hook);
if cancel_pointers {
host.app
.dispatch_window_event(WindowEvent::PointerCancel(host.wid, 0));
}
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_back_press(ptr: *mut EuvHarmonyHost) -> i32 {
if ptr.is_null() {
return 0;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let _ = host
.platform
.handle_lifecycle_hook(HarmonyLifecycleHook::OnBackPress);
drain_platform_events(host);
if host.app.get_running() { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_resize(
ptr: *mut EuvHarmonyHost,
phys_width: u32,
phys_height: u32,
density: f32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let d: f32 = density.clamp(0.75, 4.5);
host.platform.get_mut_profile().set_density(d);
host.app
.set_exact_physical_viewport(phys_width.max(1), phys_height.max(1), d);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_set_avoid_area(
ptr: *mut EuvHarmonyHost,
top_vp: f32,
right_vp: f32,
bottom_vp: f32,
left_vp: f32,
_immersive: i32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let scale: f32 = host.platform.get_profile().get_density().max(0.75);
let avoid: HarmonyAvoidArea = HarmonyAvoidArea::new(
(top_vp.max(0.0) * scale).round() as u32,
(right_vp.max(0.0) * scale).round() as u32,
(bottom_vp.max(0.0) * scale).round() as u32,
(left_vp.max(0.0) * scale).round() as u32,
0,
);
host.platform.update_avoid_area(avoid);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_config_update(
ptr: *mut EuvHarmonyHost,
is_dark: i32,
locale: *const c_char,
density: f32,
fold_tag: i32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let theme: ThemeMode = if is_dark != 0 {
ThemeMode::Dark
} else {
ThemeMode::Light
};
let fold_state: Option<HarmonyFoldState> = match fold_tag {
1 => Some(HarmonyFoldState::Expanded),
2 => Some(HarmonyFoldState::Folded),
3 => Some(HarmonyFoldState::HalfFolded),
_ => None,
};
let _ = host
.platform
.handle_lifecycle_hook(HarmonyLifecycleHook::OnConfigurationUpdate {
theme,
locale: cstr_or_empty(locale),
density,
fold_state,
});
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_memory_level(ptr: *mut EuvHarmonyHost, level: i32) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let _ = host
.platform
.handle_lifecycle_hook(HarmonyLifecycleHook::OnMemoryLevel(level));
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_keyboard_height(ptr: *mut EuvHarmonyHost, height_vp: f32) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let h: f32 = height_vp.max(0.0);
host.app
.dispatch_system_event(SystemEvent::KeyboardVisibilityChanged {
visible: h > 0.0,
height: h,
});
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_text_input(ptr: *mut EuvHarmonyHost, text: *const c_char) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let s: String = cstr_or_empty(text);
host.platform.handle_ime_commit(s);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_touch(
ptr: *mut EuvHarmonyHost,
touch_type: i32,
pointer_id: i32,
phys_x: f32,
phys_y: f32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let _ = host
.platform
.handle_touch_event(touch_type, pointer_id, phys_x, phys_y);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_mouse(
ptr: *mut EuvHarmonyHost,
action: i32,
button: i32,
phys_x: f32,
phys_y: f32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let _ = host
.platform
.handle_mouse_event(action, button, phys_x, phys_y);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_scroll(ptr: *mut EuvHarmonyHost, dx: f32, dy: f32) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let _ = host.platform.handle_scroll_event(dx, dy);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_key(
ptr: *mut EuvHarmonyHost,
key_code: i32,
is_down: i32,
shift: i32,
ctrl: i32,
alt: i32,
meta: i32,
repeat: i32,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let mut mods: Modifiers = Modifiers::default();
mods.set_shift(shift != 0);
mods.set_ctrl(ctrl != 0);
mods.set_alt(alt != 0);
mods.set_meta(meta != 0);
let _ = host
.platform
.handle_key_event_with_modifiers(key_code, is_down != 0, mods, repeat != 0);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_crown(ptr: *mut EuvHarmonyHost, delta: f32) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let _ = host.platform.handle_crown_event(delta);
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_window_mode(ptr: *mut EuvHarmonyHost, mode_tag: i32) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let mode: HarmonyWindowMode = match mode_tag {
0 => HarmonyWindowMode::Fullscreen,
1 => HarmonyWindowMode::Floating,
2 => HarmonyWindowMode::Maximized,
3 => HarmonyWindowMode::Minimized,
4 => HarmonyWindowMode::SplitPrimary,
5 => HarmonyWindowMode::SplitSecondary,
_ => HarmonyWindowMode::Floating,
};
let _ = host
.platform
.handle_lifecycle_hook(HarmonyLifecycleHook::OnWindowModeChanged(mode));
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_network(ptr: *mut EuvHarmonyHost, status_tag: i32) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let status: NetworkStatus = match status_tag {
0 => NetworkStatus::Offline,
2 => NetworkStatus::Cellular,
_ => NetworkStatus::Wifi,
};
let _ = host
.platform
.handle_lifecycle_hook(HarmonyLifecycleHook::OnNetworkStatusChanged(status));
drain_platform_events(host);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_device_motion(
ptr: *mut EuvHarmonyHost,
gx: f32,
gy: f32,
gz: f32,
lx: f32,
ly: f32,
lz: f32,
wx: f32,
wy: f32,
wz: f32,
timestamp_ns: u64,
) {
if ptr.is_null() {
return;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let roll: f32 = gx.atan2(gy);
let pitch: f32 = (-gz).atan2(gx.hypot(gy));
let sample: DeviceMotionSample = DeviceMotionSample::from_vectors(
[gx, gy, gz],
[lx, ly, lz],
[wx, wy, wz],
[pitch, roll, 0.0],
timestamp_ns,
true,
);
host.app
.dispatch_window_event(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_is_paused(ptr: *mut EuvHarmonyHost) -> i32 {
if ptr.is_null() {
return 1;
}
let host: &EuvHarmonyHost = unsafe { &*ptr };
if host.platform.is_frame_pump_paused() { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_render_rgba(
ptr: *mut EuvHarmonyHost,
dt_sec: f32,
out_pixels: *mut *const u8,
out_w: *mut u32,
out_h: *mut u32,
out_dx: *mut u32,
out_dy: *mut u32,
out_dw: *mut u32,
out_dh: *mut u32,
) -> i32 {
if ptr.is_null() {
return 0;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
if host.platform.is_frame_pump_paused() {
return 0;
}
drain_platform_events(host);
let Ok(stats) = host.app.step_game_frame(dt_sec.clamp(1.0 / 480.0, 0.05)) else {
return 0;
};
if stats.get_pixels_shaded() == 0 {
return 0;
}
let Some(fb) = host.app.get_renderer().framebuffer() else {
return 0;
};
let w: u32 = fb.get_width();
let h: u32 = fb.get_height();
let damage: DamageRegion = host.app.last_frame_damage();
let (dx, dy, dw, dh): (u32, u32, u32, u32) = if damage.get_full_damage() {
(0, 0, w, h)
} else if let Some(r) = damage.bounds_rect() {
let rx: u32 = (r.get_x().floor().max(0.0) as u32).min(w);
let ry: u32 = (r.get_y().floor().max(0.0) as u32).min(h);
let rw: u32 = (r.get_width().ceil().max(1.0) as u32).min(w.saturating_sub(rx));
let rh: u32 = (r.get_height().ceil().max(1.0) as u32).min(h.saturating_sub(ry));
(rx, ry, rw, rh)
} else {
(0, 0, w, h)
};
unsafe {
if !out_pixels.is_null() {
*out_pixels = fb.get_pixels().as_ptr();
}
if !out_w.is_null() { *out_w = w; }
if !out_h.is_null() { *out_h = h; }
if !out_dx.is_null() { *out_dx = dx; }
if !out_dy.is_null() { *out_dy = dy; }
if !out_dw.is_null() { *out_dw = dw; }
if !out_dh.is_null() { *out_dh = dh; }
}
1
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_step_frame(
ptr: *mut EuvHarmonyHost,
dt_sec: f32,
) -> i32 {
if ptr.is_null() {
return 0;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
if host.platform.is_frame_pump_paused() {
return 0;
}
drain_platform_events(host);
let Ok(stats) = host.app.step_game_frame(dt_sec.clamp(1.0 / 480.0, 0.05)) else {
return 0;
};
if stats.get_pixels_shaded() == 0 || host.native_window == 0 {
return 0;
}
let damage: DamageRegion = host.app.last_frame_damage();
if let Some(fb) = host.app.get_renderer().framebuffer() {
match host.platform.present_framebuffer_region(host.wid, fb, damage) {
Ok(()) => return 1,
Err(_) => return -1,
}
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_drain_commands_json(
ptr: *mut EuvHarmonyHost,
) -> *const c_char {
if ptr.is_null() {
return c"[]".as_ptr();
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
let mut items: Vec<String> = Vec::new();
for cmd in host.platform.drain_host_commands() {
let (kind, a1, a2): (&str, String, String) = match cmd {
HarmonyHostCommand::SetWindowTitle(t) => ("harmony_window_title", t, String::new()),
HarmonyHostCommand::SetWindowMode(m) => {
let label: &str = match m {
HarmonyWindowMode::Fullscreen => "fullscreen",
HarmonyWindowMode::Maximized => "maximize",
HarmonyWindowMode::Minimized => "minimize",
_ => "floating",
};
("harmony_window_mode", label.to_string(), String::new())
}
HarmonyHostCommand::SetDecorations(on) => {
("harmony_decorations", if on { "on" } else { "off" }.to_string(), String::new())
}
HarmonyHostCommand::SetAlwaysOnTop(on) => {
("harmony_always_on_top", if on { "on" } else { "off" }.to_string(), String::new())
}
HarmonyHostCommand::SetCursor(c) => (
"harmony_cursor",
harmony_cursor_to_pointer_style(c).to_string(),
String::new(),
),
HarmonyHostCommand::SetIme { enabled, .. } => (
"ime",
if enabled { "show" } else { "hide" }.to_string(),
String::new(),
),
HarmonyHostCommand::SetClipboard(txt) => ("clipboard", String::new(), txt),
HarmonyHostCommand::VibrateShort => ("haptic", "short".to_string(), String::new()),
HarmonyHostCommand::SetWindowSize { width, height } => (
"harmony_window_size",
width.to_string(),
height.to_string(),
),
HarmonyHostCommand::CloseWindow(id) => (
"harmony_window_close",
id.get_value().to_string(),
String::new(),
),
};
items.push(format!(
"{{\"kind\":\"{}\",\"arg1\":\"{}\",\"arg2\":\"{}\"}}",
escape_json(kind),
escape_json(&a1),
escape_json(&a2)
));
}
if let Some(q) = HARMONY_ACTIONS.get()
&& let Ok(mut guard) = q.lock()
{
for (k, a1, a2) in guard.drain(..) {
items.push(format!(
"{{\"kind\":\"{}\",\"arg1\":\"{}\",\"arg2\":\"{}\"}}",
escape_json(&k),
escape_json(&a1),
escape_json(&a2)
));
}
}
let json: String = format!("[{}]", items.join(","));
host.last_commands_cstr = CString::new(json).unwrap_or_else(|_| CString::new("[]").unwrap());
host.last_commands_cstr.as_ptr()
}