euv-cli 0.50.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <ace/xcomponent/native_xcomponent_key_event.h>
#include <napi/native_api.h>
#include <native_vsync/native_vsync.h>
#include <native_window/external_window.h>

#include <atomic>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <string>

struct EuvHarmonyHost;

extern "C" {
EuvHarmonyHost *euv_harmony_host_create(const char *device_type, uint32_t phys_w, uint32_t phys_h, float density);
void euv_harmony_host_destroy(EuvHarmonyHost *ptr);
void euv_harmony_host_attach_surface(EuvHarmonyHost *ptr, void *native_window, void *xcomponent, uint32_t phys_w, uint32_t phys_h);
void euv_harmony_host_detach_surface(EuvHarmonyHost *ptr);
void euv_harmony_host_lifecycle(EuvHarmonyHost *ptr, int32_t hook_tag, const char *payload);
int32_t euv_harmony_host_back_press(EuvHarmonyHost *ptr);
void euv_harmony_host_resize(EuvHarmonyHost *ptr, uint32_t phys_w, uint32_t phys_h, float density);
void euv_harmony_host_set_avoid_area(EuvHarmonyHost *ptr, float top_vp, float right_vp, float bottom_vp, float left_vp, int32_t immersive);
void euv_harmony_host_config_update(EuvHarmonyHost *ptr, int32_t is_dark, const char *locale, float density, int32_t fold_tag);
void euv_harmony_host_memory_level(EuvHarmonyHost *ptr, int32_t level);
void euv_harmony_host_keyboard_height(EuvHarmonyHost *ptr, float height_vp);
void euv_harmony_host_text_input(EuvHarmonyHost *ptr, const char *text);
void euv_harmony_host_touch(EuvHarmonyHost *ptr, int32_t touch_type, int32_t pointer_id, float phys_x, float phys_y);
void euv_harmony_host_mouse(EuvHarmonyHost *ptr, int32_t action, int32_t button, float phys_x, float phys_y);
void euv_harmony_host_scroll(EuvHarmonyHost *ptr, float dx, float dy);
void euv_harmony_host_key(EuvHarmonyHost *ptr, int32_t key_code, int32_t is_down, int32_t shift, int32_t ctrl, int32_t alt, int32_t meta, int32_t repeat);
void euv_harmony_host_crown(EuvHarmonyHost *ptr, float delta);
void euv_harmony_host_window_mode(EuvHarmonyHost *ptr, int32_t mode_tag);
void euv_harmony_host_network(EuvHarmonyHost *ptr, int32_t status_tag);
void euv_harmony_host_device_motion(
    EuvHarmonyHost *ptr,
    float gx, float gy, float gz,
    float lx, float ly, float lz,
    float wx, float wy, float wz,
    uint64_t timestamp_ns);
int32_t euv_harmony_host_render_rgba(
    EuvHarmonyHost *ptr,
    float dt_sec,
    const uint8_t **out_pixels,
    uint32_t *out_w,
    uint32_t *out_h,
    uint32_t *out_dx,
    uint32_t *out_dy,
    uint32_t *out_dw,
    uint32_t *out_dh);
int32_t euv_harmony_host_step_frame(EuvHarmonyHost *ptr, float dt_sec);
const char *euv_harmony_host_drain_commands_json(EuvHarmonyHost *ptr);
int32_t euv_harmony_host_is_paused(EuvHarmonyHost *ptr);
}

namespace {

struct HarmonyEglState {
    EGLDisplay display = EGL_NO_DISPLAY;
    EGLContext context = EGL_NO_CONTEXT;
    EGLSurface surface = EGL_NO_SURFACE;
    GLuint program = 0;
    GLuint vao = 0;
    GLuint texture = 0;
    uint32_t tex_w = 0;
    uint32_t tex_h = 0;
    bool ready = false;
};

static std::mutex g_host_mutex;
static EuvHarmonyHost *g_active_host = nullptr;
static void *g_active_window = nullptr;
static OH_NativeXComponent *g_active_xcomponent = nullptr;
static OH_NativeVSync *g_vsync = nullptr;
static std::atomic<bool> g_vsync_armed{false};
static int64_t g_last_vsync_ns = 0;
static HarmonyEglState g_egl;

static const char *kBlitVs =
    "#version 300 es\n"
    "out vec2 v_uv;\n"
    "void main() {\n"
    "  vec2 p = vec2((gl_VertexID == 1) ? 3.0 : -1.0, (gl_VertexID == 2) ? -3.0 : 1.0);\n"
    "  v_uv = vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5);\n"
    "  gl_Position = vec4(p, 0.0, 1.0);\n"
    "}\n";

static const char *kBlitFs =
    "#version 300 es\n"
    "precision mediump float;\n"
    "in vec2 v_uv;\n"
    "uniform sampler2D u_tex;\n"
    "out vec4 o_color;\n"
    "void main() {\n"
    "  o_color = texture(u_tex, v_uv);\n"
    "}\n";

static GLuint compileShader(GLenum type, const char *src) {
    GLuint shader = glCreateShader(type);
    glShaderSource(shader, 1, &src, nullptr);
    glCompileShader(shader);
    GLint ok = 0;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
    if (!ok) {
        glDeleteShader(shader);
        return 0;
    }
    return shader;
}

static void destroyEglLocked() {
    if (g_egl.display != EGL_NO_DISPLAY) {
        eglMakeCurrent(g_egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        if (g_egl.texture) glDeleteTextures(1, &g_egl.texture);
        if (g_egl.vao) glDeleteVertexArrays(1, &g_egl.vao);
        if (g_egl.program) glDeleteProgram(g_egl.program);
        if (g_egl.surface != EGL_NO_SURFACE) eglDestroySurface(g_egl.display, g_egl.surface);
        if (g_egl.context != EGL_NO_CONTEXT) eglDestroyContext(g_egl.display, g_egl.context);
        eglTerminate(g_egl.display);
    }
    g_egl = HarmonyEglState{};
}

static bool initEglLocked(void *native_window) {
    destroyEglLocked();
    if (!native_window) return false;
    EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (dpy == EGL_NO_DISPLAY || !eglInitialize(dpy, nullptr, nullptr)) return false;
    const EGLint cfg_attribs[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_NONE
    };
    EGLConfig cfg = nullptr;
    EGLint count = 0;
    if (!eglChooseConfig(dpy, cfg_attribs, &cfg, 1, &count) || count < 1) {
        eglTerminate(dpy);
        return false;
    }
    const EGLint ctx_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
    EGLContext ctx = eglCreateContext(dpy, cfg, EGL_NO_CONTEXT, ctx_attribs);
    EGLSurface surf = eglCreateWindowSurface(dpy, cfg, reinterpret_cast<EGLNativeWindowType>(native_window), nullptr);
    if (ctx == EGL_NO_CONTEXT || surf == EGL_NO_SURFACE || !eglMakeCurrent(dpy, surf, surf, ctx)) {
        if (surf != EGL_NO_SURFACE) eglDestroySurface(dpy, surf);
        if (ctx != EGL_NO_CONTEXT) eglDestroyContext(dpy, ctx);
        eglTerminate(dpy);
        return false;
    }
    eglSwapInterval(dpy, 1);
    GLuint vs = compileShader(GL_VERTEX_SHADER, kBlitVs);
    GLuint fs = compileShader(GL_FRAGMENT_SHADER, kBlitFs);
    GLuint prog = glCreateProgram();
    glAttachShader(prog, vs);
    glAttachShader(prog, fs);
    glLinkProgram(prog);
    glDeleteShader(vs);
    glDeleteShader(fs);
    GLint linked = 0;
    glGetProgramiv(prog, GL_LINK_STATUS, &linked);
    if (!linked) {
        glDeleteProgram(prog);
        eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        eglDestroySurface(dpy, surf);
        eglDestroyContext(dpy, ctx);
        eglTerminate(dpy);
        return false;
    }
    GLuint vao = 0;
    GLuint tex = 0;
    glGenVertexArrays(1, &vao);
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    g_egl.display = dpy;
    g_egl.context = ctx;
    g_egl.surface = surf;
    g_egl.program = prog;
    g_egl.vao = vao;
    g_egl.texture = tex;
    g_egl.ready = true;
    return true;
}

static bool presentEglLocked(const uint8_t *pixels, uint32_t w, uint32_t h, uint32_t dx, uint32_t dy, uint32_t dw, uint32_t dh) {
    if (!g_egl.ready || !pixels || w == 0 || h == 0) return false;
    if (!eglMakeCurrent(g_egl.display, g_egl.surface, g_egl.surface, g_egl.context)) return false;
    glBindTexture(GL_TEXTURE_2D, g_egl.texture);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    if (g_egl.tex_w != w || g_egl.tex_h != h) {
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(w), static_cast<GLsizei>(h), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
        g_egl.tex_w = w;
        g_egl.tex_h = h;
    } else if (dw > 0 && dh > 0 && dx + dw <= w && dy + dh <= h && !(dx == 0 && dy == 0 && dw == w && dh == h)) {
        glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(w));
        const uint8_t *sub = pixels + (static_cast<size_t>(dy) * static_cast<size_t>(w) + static_cast<size_t>(dx)) * 4u;
        glTexSubImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(dx), static_cast<GLint>(dy), static_cast<GLsizei>(dw), static_cast<GLsizei>(dh), GL_RGBA, GL_UNSIGNED_BYTE, sub);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    } else {
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    }
    glViewport(0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h));
    glUseProgram(g_egl.program);
    glBindVertexArray(g_egl.vao);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, g_egl.texture);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    return eglSwapBuffers(g_egl.display, g_egl.surface) == EGL_TRUE;
}

static void onVsyncCallback(long long timestamp_ns, void *data);

static void armVsyncLocked() {
    if (!g_vsync || g_vsync_armed.load() || !g_active_host || !g_active_window) return;
    if (euv_harmony_host_is_paused(g_active_host) != 0) return;
    g_vsync_armed.store(true);
    OH_NativeVSync_RequestFrame(g_vsync, onVsyncCallback, nullptr);
}

static void onVsyncCallback(long long timestamp_ns, void * /*data*/) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_vsync_armed.store(false);
    if (!g_active_host || !g_active_window || euv_harmony_host_is_paused(g_active_host) != 0) {
        return;
    }
    float dt = 1.0f / 60.0f;
    if (g_last_vsync_ns > 0 && timestamp_ns > g_last_vsync_ns) {
        dt = static_cast<float>(timestamp_ns - g_last_vsync_ns) / 1.0e9f;
        if (dt < 0.002f) dt = 0.002f;
        if (dt > 0.05f) dt = 0.05f;
    }
    g_last_vsync_ns = timestamp_ns;
    if (g_egl.ready) {
        const uint8_t *px = nullptr;
        uint32_t w = 0, h = 0, dx = 0, dy = 0, dw = 0, dh = 0;
        int32_t rendered = euv_harmony_host_render_rgba(g_active_host, dt, &px, &w, &h, &dx, &dy, &dw, &dh);
        if (rendered > 0 && px != nullptr) {
            presentEglLocked(px, w, h, dx, dy, dw, dh);
        }
    } else {
        euv_harmony_host_step_frame(g_active_host, dt);
    }
    armVsyncLocked();
}

static void onSurfaceCreatedCB(OH_NativeXComponent *component, void *window) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_active_xcomponent = component;
    g_active_window = window;
    uint64_t w = 0, h = 0;
    OH_NativeXComponent_GetXComponentSize(component, window, &w, &h);
    initEglLocked(window);
    if (g_active_host) {
        euv_harmony_host_attach_surface(g_active_host, window, component, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
    }
    if (!g_vsync) {
        const char *name = "euv_harmony_vsync";
        g_vsync = OH_NativeVSync_Create(name, static_cast<unsigned int>(std::strlen(name)));
    }
    armVsyncLocked();
}

static void onSurfaceChangedCB(OH_NativeXComponent *component, void *window) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_active_window = window;
    uint64_t w = 0, h = 0;
    OH_NativeXComponent_GetXComponentSize(component, window, &w, &h);
    if (g_active_host) {
        euv_harmony_host_attach_surface(g_active_host, window, component, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
    }
    armVsyncLocked();
}

static void onSurfaceDestroyedCB(OH_NativeXComponent * /*component*/, void * /*window*/) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_active_window = nullptr;
    destroyEglLocked();
    if (g_active_host) {
        euv_harmony_host_detach_surface(g_active_host);
    }
}

static void dispatchTouchEventCB(OH_NativeXComponent *component, void *window) {
    OH_NativeXComponent_TouchEvent ev{};
    if (OH_NativeXComponent_GetTouchEvent(component, window, &ev) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        return;
    }
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (!g_active_host) return;
    if (ev.numPoints > 0) {
        uint32_t count = ev.numPoints < OH_MAX_TOUCH_POINTS_NUMBER ? ev.numPoints : OH_MAX_TOUCH_POINTS_NUMBER;
        for (uint32_t i = 0; i < count; ++i) {
            const auto &pt = ev.touchPoints[i];
            euv_harmony_host_touch(g_active_host, static_cast<int32_t>(pt.type), pt.id, pt.x, pt.y);
        }
    } else {
        euv_harmony_host_touch(g_active_host, static_cast<int32_t>(ev.type), ev.id, ev.x, ev.y);
    }
    armVsyncLocked();
}

static void dispatchMouseEventCB(OH_NativeXComponent *component, void *window) {
    OH_NativeXComponent_MouseEvent ev{};
    if (OH_NativeXComponent_GetMouseEvent(component, window, &ev) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        return;
    }
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (!g_active_host) return;
    euv_harmony_host_mouse(g_active_host, static_cast<int32_t>(ev.action), static_cast<int32_t>(ev.button), ev.x, ev.y);
    armVsyncLocked();
}

static void dispatchHoverEventCB(OH_NativeXComponent * /*component*/, bool /*isHover*/) {}

static void dispatchKeyEventCB(OH_NativeXComponent *component, void * /*window*/) {
    OH_NativeXComponent_KeyEvent *keyEvent = nullptr;
    if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS || !keyEvent) {
        return;
    }
    OH_NativeXComponent_KeyAction action = OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN;
    OH_NativeXComponent_KeyCode code = KEY_UNKNOWN;
    OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
    OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (!g_active_host) return;
    bool is_down = (action == OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN);
    euv_harmony_host_key(g_active_host, static_cast<int32_t>(code), is_down ? 1 : 0, 0, 0, 0, 0, 0);
    armVsyncLocked();
}

static OH_NativeXComponent_Callback g_xc_callbacks = {
    onSurfaceCreatedCB,
    onSurfaceChangedCB,
    onSurfaceDestroyedCB,
    dispatchTouchEventCB
};

static OH_NativeXComponent_MouseEvent_Callback g_mouse_callbacks = {
    dispatchMouseEventCB,
    dispatchHoverEventCB
};

static std::string getNapiString(napi_env env, napi_value val) {
    size_t len = 0;
    if (napi_get_value_string_utf8(env, val, nullptr, 0, &len) != napi_ok || len == 0) {
        return {};
    }
    std::string out(len, '\0');
    napi_get_value_string_utf8(env, val, out.data(), len + 1, &len);
    return out;
}

static EuvHarmonyHost *getHostFromArg(napi_env env, napi_value val) {
    int64_t raw = 0;
    if (napi_get_value_int64(env, val, &raw) != napi_ok || raw == 0) return nullptr;
    return reinterpret_cast<EuvHarmonyHost *>(static_cast<uintptr_t>(raw));
}

static napi_value napiCreate(napi_env env, napi_callback_info info) {
    size_t argc = 4;
    napi_value argv[4];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::string dev = argc >= 1 ? getNapiString(env, argv[0]) : "phone";
    uint32_t w = 1080, h = 2340;
    double d = 3.0;
    if (argc >= 2) napi_get_value_uint32(env, argv[1], &w);
    if (argc >= 3) napi_get_value_uint32(env, argv[2], &h);
    if (argc >= 4) napi_get_value_double(env, argv[3], &d);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = euv_harmony_host_create(dev.c_str(), w, h, static_cast<float>(d));
    g_active_host = host;
    if (host && g_active_window && g_active_xcomponent) {
        uint64_t sw = w, sh = h;
        OH_NativeXComponent_GetXComponentSize(g_active_xcomponent, g_active_window, &sw, &sh);
        euv_harmony_host_attach_surface(host, g_active_window, g_active_xcomponent, static_cast<uint32_t>(sw), static_cast<uint32_t>(sh));
        armVsyncLocked();
    }
    napi_value res = nullptr;
    napi_create_int64(env, static_cast<int64_t>(reinterpret_cast<uintptr_t>(host)), &res);
    return res;
}

static napi_value napiDestroy(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    if (host == g_active_host) g_active_host = nullptr;
    if (g_vsync) {
        OH_NativeVSync_Destroy(g_vsync);
        g_vsync = nullptr;
    }
    destroyEglLocked();
    euv_harmony_host_destroy(host);
    return nullptr;
}

static napi_value napiOnLifecycle(napi_env env, napi_callback_info info) {
    size_t argc = 3;
    napi_value argv[3];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    std::string hook = argc >= 2 ? getNapiString(env, argv[1]) : "";
    std::string payload = argc >= 3 ? getNapiString(env, argv[2]) : "";
    int32_t tag = 0;
    if (hook == "onCreate") tag = 1;
    else if (hook == "onForeground") tag = 2;
    else if (hook == "onWindowActive") tag = 3;
    else if (hook == "onWindowInactive") tag = 4;
    else if (hook == "onBackground") tag = 5;
    else if (hook == "onWindowStageDestroy") tag = 6;
    else if (hook == "onDestroy") tag = 7;
    else if (hook == "onBackPress") tag = 8;
    else if (hook == "onNewWant") tag = 9;
    if (host && tag != 0) {
        euv_harmony_host_lifecycle(host, tag, payload.c_str());
        if (tag == 2 || tag == 3) armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiSetAvoidArea(napi_env env, napi_callback_info info) {
    size_t argc = 6;
    napi_value argv[6];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double top = 0, right = 0, bottom = 0, left = 0;
    bool imm = false;
    if (argc >= 2) napi_get_value_double(env, argv[1], &top);
    if (argc >= 3) napi_get_value_double(env, argv[2], &right);
    if (argc >= 4) napi_get_value_double(env, argv[3], &bottom);
    if (argc >= 5) napi_get_value_double(env, argv[4], &left);
    if (argc >= 6) napi_get_value_bool(env, argv[5], &imm);
    if (host) {
        euv_harmony_host_set_avoid_area(host, static_cast<float>(top), static_cast<float>(right), static_cast<float>(bottom), static_cast<float>(left), imm ? 1 : 0);
    }
    return nullptr;
}

static napi_value napiResize(napi_env env, napi_callback_info info) {
    size_t argc = 4;
    napi_value argv[4];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    uint32_t w = 1, h = 1;
    double d = 2.0;
    if (argc >= 2) napi_get_value_uint32(env, argv[1], &w);
    if (argc >= 3) napi_get_value_uint32(env, argv[2], &h);
    if (argc >= 4) napi_get_value_double(env, argv[3], &d);
    if (host) {
        euv_harmony_host_resize(host, w, h, static_cast<float>(d));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnMemoryLevel(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t lvl = 0;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &lvl);
    if (host) euv_harmony_host_memory_level(host, lvl);
    return nullptr;
}

static napi_value napiOnConfigUpdate(napi_env env, napi_callback_info info) {
    size_t argc = 5;
    napi_value argv[5];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    bool is_dark = false;
    std::string locale = argc >= 3 ? getNapiString(env, argv[2]) : "en-US";
    double d = 2.0;
    int32_t fold = 0;
    if (argc >= 2) napi_get_value_bool(env, argv[1], &is_dark);
    if (argc >= 4) napi_get_value_double(env, argv[3], &d);
    if (argc >= 5) napi_get_value_int32(env, argv[4], &fold);
    if (host) {
        euv_harmony_host_config_update(host, is_dark ? 1 : 0, locale.c_str(), static_cast<float>(d), fold);
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnKeyboardHeight(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double h = 0.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &h);
    if (host) euv_harmony_host_keyboard_height(host, static_cast<float>(h));
    return nullptr;
}

static napi_value napiTextInput(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    std::string text = argc >= 2 ? getNapiString(env, argv[1]) : "";
    if (host && !text.empty()) {
        euv_harmony_host_text_input(host, text.c_str());
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiBackPress(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    bool handled = host ? (euv_harmony_host_back_press(host) != 0) : false;
    napi_value res = nullptr;
    napi_get_boolean(env, handled, &res);
    return res;
}

static napi_value napiOnDeviceMotion(napi_env env, napi_callback_info info) {
    size_t argc = 11;
    napi_value argv[11];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double v[9] = {0};
    int64_t ts = 0;
    for (size_t i = 0; i < 9 && (i + 1) < argc; ++i) napi_get_value_double(env, argv[i + 1], &v[i]);
    if (argc >= 11) napi_get_value_int64(env, argv[10], &ts);
    if (host) {
        euv_harmony_host_device_motion(
            host,
            static_cast<float>(v[0]), static_cast<float>(v[1]), static_cast<float>(v[2]),
            static_cast<float>(v[3]), static_cast<float>(v[4]), static_cast<float>(v[5]),
            static_cast<float>(v[6]), static_cast<float>(v[7]), static_cast<float>(v[8]),
            static_cast<uint64_t>(ts > 0 ? ts : 0));
    }
    return nullptr;
}

static napi_value napiOnMouse(napi_env env, napi_callback_info info) {
    size_t argc = 5;
    napi_value argv[5];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t action = 3, button = 0;
    double x = 0.0, y = 0.0;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &action);
    if (argc >= 3) napi_get_value_int32(env, argv[2], &button);
    if (argc >= 4) napi_get_value_double(env, argv[3], &x);
    if (argc >= 5) napi_get_value_double(env, argv[4], &y);
    if (host) {
        euv_harmony_host_mouse(host, action, button, static_cast<float>(x), static_cast<float>(y));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnScroll(napi_env env, napi_callback_info info) {
    size_t argc = 3;
    napi_value argv[3];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double dx = 0.0, dy = 0.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &dx);
    if (argc >= 3) napi_get_value_double(env, argv[2], &dy);
    if (host) {
        euv_harmony_host_scroll(host, static_cast<float>(dx), static_cast<float>(dy));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnKey(napi_env env, napi_callback_info info) {
    size_t argc = 8;
    napi_value argv[8];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t code = 0;
    bool down = false, sh = false, ct = false, al = false, mt = false, rp = false;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &code);
    if (argc >= 3) napi_get_value_bool(env, argv[2], &down);
    if (argc >= 4) napi_get_value_bool(env, argv[3], &sh);
    if (argc >= 5) napi_get_value_bool(env, argv[4], &ct);
    if (argc >= 6) napi_get_value_bool(env, argv[5], &al);
    if (argc >= 7) napi_get_value_bool(env, argv[6], &mt);
    if (argc >= 8) napi_get_value_bool(env, argv[7], &rp);
    if (host) {
        euv_harmony_host_key(host, code, down ? 1 : 0, sh ? 1 : 0, ct ? 1 : 0, al ? 1 : 0, mt ? 1 : 0, rp ? 1 : 0);
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnCrown(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double delta = 0.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &delta);
    if (host) {
        euv_harmony_host_crown(host, static_cast<float>(delta));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnWindowMode(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t mode = 0;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &mode);
    if (host) euv_harmony_host_window_mode(host, mode);
    return nullptr;
}

static napi_value napiOnNetwork(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t st = 1;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &st);
    if (host) euv_harmony_host_network(host, st);
    return nullptr;
}

static napi_value napiDrainHostCommands(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    const char *json = host ? euv_harmony_host_drain_commands_json(host) : "[]";
    napi_value res = nullptr;
    napi_create_string_utf8(env, json ? json : "[]", NAPI_AUTO_LENGTH, &res);
    return res;
}

static napi_value napiStepFrame(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double dt = 1.0 / 60.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &dt);
    int32_t rc = 0;
    if (host) {
        if (g_egl.ready) {
            const uint8_t *px = nullptr;
            uint32_t w = 0, h = 0, dx = 0, dy = 0, dw = 0, dh = 0;
            rc = euv_harmony_host_render_rgba(host, static_cast<float>(dt), &px, &w, &h, &dx, &dy, &dw, &dh);
            if (rc > 0 && px != nullptr) presentEglLocked(px, w, h, dx, dy, dw, dh);
        } else {
            rc = euv_harmony_host_step_frame(host, static_cast<float>(dt));
        }
    }
    napi_value res = nullptr;
    napi_create_int32(env, rc, &res);
    return res;
}

static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        { "euvHarmonyCreate", nullptr, napiCreate, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyDestroy", nullptr, napiDestroy, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnLifecycle", nullptr, napiOnLifecycle, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonySetAvoidArea", nullptr, napiSetAvoidArea, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyResize", nullptr, napiResize, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnMemoryLevel", nullptr, napiOnMemoryLevel, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnConfigUpdate", nullptr, napiOnConfigUpdate, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnKeyboardHeight", nullptr, napiOnKeyboardHeight, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyTextInput", nullptr, napiTextInput, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyBackPress", nullptr, napiBackPress, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnDeviceMotion", nullptr, napiOnDeviceMotion, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnMouse", nullptr, napiOnMouse, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnScroll", nullptr, napiOnScroll, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnKey", nullptr, napiOnKey, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnCrown", nullptr, napiOnCrown, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnWindowMode", nullptr, napiOnWindowMode, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnNetwork", nullptr, napiOnNetwork, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyDrainHostCommands", nullptr, napiDrainHostCommands, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyStepFrame", nullptr, napiStepFrame, nullptr, nullptr, nullptr, napi_default, nullptr },
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);

    napi_value xc_val = nullptr;
    if (napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &xc_val) == napi_ok && xc_val != nullptr) {
        OH_NativeXComponent *xc = nullptr;
        if (napi_unwrap(env, xc_val, reinterpret_cast<void **>(&xc)) == napi_ok && xc != nullptr) {
            OH_NativeXComponent_RegisterCallback(xc, &g_xc_callbacks);
            OH_NativeXComponent_RegisterMouseEventCallback(xc, &g_mouse_callbacks);
            OH_NativeXComponent_RegisterKeyEventCallback(xc, dispatchKeyEventCB);
        }
    }
    return exports;
}

static napi_module g_euv_harmony_module = {
    1,
    0,
    nullptr,
    Init,
    "euv_harmony_host",
    nullptr,
    { nullptr },
};

} // namespace

extern "C" __attribute__((constructor)) void RegisterEuvHarmonyHostModule(void) {
    napi_module_register(&g_euv_harmony_module);
}