mod host_config;
use std::ffi::{CStr, CString, c_char, c_void};
use std::sync::{Mutex, OnceLock};
use euv::{
App, DamageRegion, DeviceMotionSample, DirectGpuBatchRange, DirectGpuFrameBatch, DisplayList,
GLSL_ES3_UI_FRAGMENT_SHADER, GLSL_ES3_UI_VERTEX_SHADER, GpuPrimitiveInstance,
HarmonyAvoidArea, HarmonyDeviceType, HarmonyFoldState, HarmonyHostCommand,
HarmonyLifecycleHook, HarmonyPlatform, HarmonyWindowMode, Modifiers, NativeSystemFont,
NetworkStatus, PlatformBackend, PlatformKind, RenderMode, SystemEvent, ThemeMode, WindowConfig,
WindowEvent, WindowId, compile_display_list_direct_gpu_batch, harmony_cursor_to_pointer_style,
is_frame_needed, 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
}
#[repr(C)]
pub struct EuvHarmonyDirectFrameDesc {
pub viewport_w: u32,
pub viewport_h: u32,
pub clear_rgba: [f32; 4],
pub primitives_ptr: *const GpuPrimitiveInstance,
pub primitives_len: usize,
pub ranges_ptr: *const DirectGpuBatchRange,
pub ranges_len: usize,
pub glyph_r8_ptr: *const u8,
pub glyph_r8_w: u32,
pub glyph_r8_h: u32,
pub glyph_r8_rev: u64,
pub glyph_r8_dirty_y: u32,
pub glyph_r8_dirty_h: u32,
pub image_rgba8_ptr: *const u8,
pub image_rgba8_w: u32,
pub image_rgba8_h: u32,
pub image_rgba8_rev: u64,
pub image_rgba8_dirty_y: u32,
pub image_rgba8_dirty_h: u32,
}
fn compute_dirty_row_span(
pixels: &[u8],
width: u32,
height: u32,
bytes_per_pixel: usize,
cached_w: &mut u32,
cached_h: &mut u32,
row_hashes: &mut Vec<u64>,
) -> (u32, u32) {
if width == 0 || height == 0 {
return (0, 0);
}
let row_bytes: usize = (width as usize).saturating_mul(bytes_per_pixel);
if pixels.len() < row_bytes.saturating_mul(height as usize) {
return (0, 0);
}
let resized: bool = *cached_w != width || *cached_h != height || row_hashes.len() != (height as usize);
if resized {
*cached_w = width;
*cached_h = height;
row_hashes.clear();
row_hashes.resize(height as usize, 0);
}
let mut first_dirty: Option<u32> = None;
let mut last_dirty: u32 = 0;
for row in 0..(height as usize) {
let start: usize = row * row_bytes;
let slice: &[u8] = &pixels[start..start + row_bytes];
let mut hash: u64 = 0xcbf2_9ce4_8422_2325u64;
for chunk in slice.chunks_exact(8) {
let word: u64 = u64::from_ne_bytes([
chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
]);
hash = (hash ^ word).wrapping_mul(0x0000_0100_0000_01b3u64);
}
for &byte in slice.chunks_exact(8).remainder() {
hash = (hash ^ (byte as u64)).wrapping_mul(0x0000_0100_0000_01b3u64);
}
if resized || row_hashes[row] != hash {
row_hashes[row] = hash;
if first_dirty.is_none() {
first_dirty = Some(row as u32);
}
last_dirty = row as u32;
}
}
if resized {
return (0, height);
}
match first_dirty {
Some(y0) => (y0, last_dirty.saturating_sub(y0).saturating_add(1)),
None => (0, 0),
}
}
pub struct EuvHarmonyHost {
app: App,
_state: ShowcaseState,
platform: HarmonyPlatform,
wid: WindowId,
native_window: usize,
width: u32,
height: u32,
font_provider: NativeSystemFont,
direct_batch: DirectGpuFrameBatch,
uploaded_glyph_revision: u64,
glyph_atlas_w: u32,
glyph_atlas_h: u32,
glyph_row_hashes: Vec<u64>,
uploaded_image_revision: u64,
image_atlas_w: u32,
image_atlas_h: u32,
image_row_hashes: Vec<u64>,
gles3_vs_cstr: CString,
gles3_fs_cstr: CString,
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.25, 16.0);
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::Auto)
else {
return std::ptr::null_mut();
};
let font_provider: NativeSystemFont = NativeSystemFont::system();
app.get_mut_renderer()
.get_mut_software()
.set_font_provider(font_provider.clone());
app.set_exact_physical_viewport(phys_width.max(1), phys_height.max(1), d);
let gles3_vs_cstr: CString =
CString::new(GLSL_ES3_UI_VERTEX_SHADER).unwrap_or_else(|_| CString::new("").unwrap());
let gles3_fs_cstr: CString =
CString::new(GLSL_ES3_UI_FRAGMENT_SHADER).unwrap_or_else(|_| CString::new("").unwrap());
let boxed: Box<EuvHarmonyHost> = Box::new(EuvHarmonyHost {
app,
_state: state,
platform,
wid,
native_window: 0,
width: 0,
height: 0,
font_provider,
direct_batch: DirectGpuFrameBatch::default(),
uploaded_glyph_revision: 0,
glyph_atlas_w: 0,
glyph_atlas_h: 0,
glyph_row_hashes: Vec::new(),
uploaded_image_revision: 0,
image_atlas_w: 0,
image_atlas_h: 0,
image_row_hashes: Vec::new(),
gles3_vs_cstr,
gles3_fs_cstr,
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.25, 16.0);
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.25, 16.0);
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_gles3_ui_vs(ptr: *mut EuvHarmonyHost) -> *const c_char {
if ptr.is_null() {
return c"".as_ptr();
}
let host: &EuvHarmonyHost = unsafe { &*ptr };
host.gles3_vs_cstr.as_ptr()
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_gles3_ui_fs(ptr: *mut EuvHarmonyHost) -> *const c_char {
if ptr.is_null() {
return c"".as_ptr();
}
let host: &EuvHarmonyHost = unsafe { &*ptr };
host.gles3_fs_cstr.as_ptr()
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_needs_frame(ptr: *mut EuvHarmonyHost) -> i32 {
if ptr.is_null() {
return 0;
}
let host: &EuvHarmonyHost = unsafe { &*ptr };
if host.platform.is_frame_pump_paused() || !host.app.get_running() {
return 0;
}
if host.width == 0
|| host.height == 0
|| host.app.has_active_animations()
|| is_frame_needed()
|| !host.app.is_idle()
{
1
} else {
0
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_has_pending_commands(ptr: *mut EuvHarmonyHost) -> i32 {
if ptr.is_null() {
return 0;
}
let host: &EuvHarmonyHost = unsafe { &*ptr };
if !host.platform.get_outbound_commands().is_empty() {
return 1;
}
if let Some(q) = HARMONY_ACTIONS.get()
&& let Ok(guard) = q.lock()
&& !guard.is_empty()
{
return 1;
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn euv_harmony_host_step_direct_gpu(
ptr: *mut EuvHarmonyHost,
dt_sec: f32,
out_desc: *mut EuvHarmonyDirectFrameDesc,
) -> i32 {
if ptr.is_null() || out_desc.is_null() {
return 0;
}
let host: &mut EuvHarmonyHost = unsafe { &mut *ptr };
if host.platform.is_frame_pump_paused() {
return 0;
}
drain_platform_events(host);
host.app.get_mut_renderer().set_direct_gpu_present(true);
let Ok(stats) = host.app.step_game_frame(dt_sec.clamp(1.0 / 480.0, 0.05)) else {
return 0;
};
let changed: bool =
stats.get_pixels_shaded() > 0 || stats.get_draw_commands() > 0 || host.width == 0;
if !changed {
return 0;
}
host.direct_batch = {
let renderer = host.app.get_mut_renderer();
let display_list: DisplayList = std::mem::take(renderer.get_mut_display_list());
let glyph_atlas = renderer.get_mut_font_service().get_mut_glyph_atlas();
let batch: DirectGpuFrameBatch = compile_display_list_direct_gpu_batch(
&display_list,
Some(glyph_atlas),
Some(&host.font_provider),
host.uploaded_glyph_revision,
);
*renderer.get_mut_display_list() = display_list;
batch
};
host.width = host.direct_batch.get_viewport_width();
host.height = host.direct_batch.get_viewport_height();
let (glyph_ptr, glyph_w, glyph_h, glyph_rev, glyph_dy, glyph_dh): (
*const u8,
u32,
u32,
u64,
u32,
u32,
) = match host.direct_batch.glyph_r8_atlas_ref() {
Some(a) if a.get_width() > 0 && a.get_height() > 0 => {
let (dy, dh): (u32, u32) = compute_dirty_row_span(
a.get_pixels(),
a.get_width(),
a.get_height(),
1,
&mut host.glyph_atlas_w,
&mut host.glyph_atlas_h,
&mut host.glyph_row_hashes,
);
host.uploaded_glyph_revision = a.get_revision();
(
a.get_pixels().as_ptr(),
a.get_width(),
a.get_height(),
a.get_revision(),
dy,
dh,
)
}
_ => (std::ptr::null(), 0, 0, host.uploaded_glyph_revision, 0, 0),
};
let (img_ptr, img_w, img_h, img_rev, img_dy, img_dh): (
*const u8,
u32,
u32,
u64,
u32,
u32,
) = match host.direct_batch.image_rgba8_atlas_ref() {
Some(a) if a.get_width() > 0 && a.get_height() > 0 => {
let rev: u64 = a.get_revision();
let (dy, dh): (u32, u32) = if rev != 0
&& rev == host.uploaded_image_revision
&& host.image_atlas_w == a.get_width()
&& host.image_atlas_h == a.get_height()
{
(0, 0)
} else {
host.uploaded_image_revision = rev;
compute_dirty_row_span(
a.get_pixels(),
a.get_width(),
a.get_height(),
4,
&mut host.image_atlas_w,
&mut host.image_atlas_h,
&mut host.image_row_hashes,
)
};
(a.get_pixels().as_ptr(), a.get_width(), a.get_height(), rev, dy, dh)
}
_ => (std::ptr::null(), 0, 0, host.uploaded_image_revision, 0, 0),
};
unsafe {
*out_desc = EuvHarmonyDirectFrameDesc {
viewport_w: host.direct_batch.get_viewport_width(),
viewport_h: host.direct_batch.get_viewport_height(),
clear_rgba: host.direct_batch.get_clear_rgba(),
primitives_ptr: host.direct_batch.get_primitives().as_ptr(),
primitives_len: host.direct_batch.get_primitives().len(),
ranges_ptr: host.direct_batch.get_draw_ranges().as_ptr(),
ranges_len: host.direct_batch.get_draw_ranges().len(),
glyph_r8_ptr: glyph_ptr,
glyph_r8_w: glyph_w,
glyph_r8_h: glyph_h,
glyph_r8_rev: glyph_rev,
glyph_r8_dirty_y: glyph_dy,
glyph_r8_dirty_h: glyph_dh,
image_rgba8_ptr: img_ptr,
image_rgba8_w: img_w,
image_rgba8_h: img_h,
image_rgba8_rev: img_rev,
image_rgba8_dirty_y: img_dy,
image_rgba8_dirty_h: img_dh,
};
}
1
}
#[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);
host.app.get_mut_renderer().set_direct_gpu_present(false);
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.width > 0 {
return 0;
}
if host.app.get_renderer().framebuffer().is_none() {
let _ = host
.app
.get_mut_renderer()
.capture_reference_framebuffer(DamageRegion::full());
}
let Some(fb) = host.app.get_renderer().framebuffer() else {
return 0;
};
let w: u32 = fb.get_width();
let h: u32 = fb.get_height();
host.width = w;
host.height = h;
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()
}